androidandroid-optionsmenu

Set title for options menu items


I am creating an app for multiple languages. The language switching works well, except the options menu.

I have this in my menu/main.xml:

<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
>

<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />

<item
    android:id="@+id/action_about"
    android:orderInCategory="100"
    android:title="@string/action_about"
    app:showAsAction="never" />

This causes my meni items have always the same titles, even I switch the language, because it takes it from XML.

Now I tried it to change programmatically in my MainActivity.java with item.setTitle:

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.

    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            Context context = LocaleHelper.setLocale(this, LocaleHelper.getLanguage(this));
            Resources resources = context.getResources();
            item.setTitle(resources.getString(R.string.action_settings));
            Intent i = new Intent(this,LanguageChange.class);
            this.startActivity(i);
            return true;
        case R.id.action_about:
            Context context = LocaleHelper.setLocale(this, LocaleHelper.getLanguage(this));
            Resources resources = context.getResources();
            item.setTitle(resources.getString(R.string.about_settings));
            Intent ix = new Intent(this,About.class);
            this.startActivity(ix);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

The problem is, that the title of menu items changes ONLY after I enter the menu and go back. Then the item titles are changed. But I need to change them immediately.


Solution

  • Change your items in onPrepareOptionsMenu(Menu menu) like this:

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem settings = menu.findItem(R.id.action_settings);
        // do smth with menu item
        return true;
    }