简体   繁体   中英

Can't retrieve the menu item in the ActionBar

So i have this menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:showAsAction="always"
    android:title="Settings">
</item>

I add it to the View like this:

@Override
public boolean onCreateOptionsMenu(Menu menu) {

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

And then i would like to set the Text before it really gets shown and it thought i would have to do it like this:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem item = menu.getItem(R.id.action_settings);
    item.setTitle(langRes.getTextForKey("settings"));
    return super.onPrepareOptionsMenu(menu);
}

I get an IndexOutofBoundsException and the Menu when i debug it in the onPrepareOptionsMenu doesn't contain any Items!! What am i doing wrong please?

You have to use MenuItem item = menu.findItem(R.id.action_settings); instead of MenuItem item = menu.getItem(R.id.action_settings); then your problem will resolved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM