Android & menu localization
I would like to change language (locale of application) programmatically.
The main problem for me is updating menu labels.
I tried the following method:
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
if (shouldChangeMenuLabels) {
for (int i = 0; i < menu.size(); i++) {
MenuItem menuItem = menu.getItem(i);
switch (menuItem.getItemId()) {
case R.id.menu_main_about:
menuItem.setTitle(R.string.menu_about);
break;
case R.id.menu_main_preferences:
menuItem.setTitle(R.string.menu_prefs);
break;
}
}
shouldChangeMenuLabels = false;
}
But I'm sure it bad idea. I want to avoid using switch-case statement as this is not universal method (I can't simply port the snipped to other activities / I can't make abstract class which would do that).
BTW, all menus have been described into menu/*.xml files so I don't want duplicating the code. Anybody has ideas?
Concerned to first answer: I hae changed locale with the following code:
Locale locale = new Locale((String)newValue);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getApplication().getResources().updateConfiguration(config, getApplication().getResources().getDisplayMetrics());
But as I want to control rotating for each activity, they are never fini开发者_运维技巧shed. Maybe I did something wrong?
I don't know is it a good idea, but I've found following way:
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
if (shouldChangeLocale) {
menu.clear();
MenuInflater inflater = getMenuInflater(); // -->onCreateMenu (Menu)
inflater.inflate(R.menu.menu_main, menu); // /
shouldChangeLocale=false;
}
return super.onMenuOpened(featureId, menu);
}
I need your advice, should I do this such way?
Have you read through the documentation on Android Localization? Typically you create a different strings file for each language/locale that you want to support. In your menu.xml file you can reference the string id's, and the proper value will be selected based on the current locale settings.
menu.add(0, MENU_ABOUT, 0, _mContext.getResources().getString(R.string.mymenu)).setIcon(R.drawable.ic_menu);
While creating menu insert you string and localize it.
精彩评论