Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 finished. Maybe I did something wrong?

like image 509
davs Avatar asked Aug 02 '10 21:08

davs


2 Answers

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?

like image 69
davs Avatar answered Sep 24 '22 13:09

davs


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.

like image 33
Cheryl Simon Avatar answered Sep 25 '22 13:09

Cheryl Simon