Search code examples
androidandroid-fragmentsmenuitemandroid-actionbar

onPrepareOptionsMenu Duplicates item in ActionBar


When I add a menu item using onPrepareOptionsMenu, the menu item duplicates its self in the action bar. I'm using fragments and creating the initial menu in the ActionBar in the main activity like this:

...
 @Override
    public boolean onCreateOptionsMenu(Menu paramMenu) {
    super.onCreateOptionsMenu(paramMenu);
    paramMenu.add(0, 1, 0, "DashBoard").setIcon(R.drawable.ic_dashboard)
        .setShowAsAction(1);
    return true;
    }

I'm then adding another item in one of the fragments as follows:

...
@Override
    public void onPrepareOptionsMenu(Menu paramMenu) {
    paramMenu.add(0, 2, 1, "FullScreen").setIcon(R.drawable.ic_fullscreen)
        .setShowAsAction(1);
    }

For some reason this added item via the fragment class displays twice.... Do i have something wrong?

Any help to what I have wrong will be appreciated


Solution

  • The item is probably displaying twice because you're adding it twice. See the docs for onPrepareOptionsMenu:

    This is called right before the menu is shown, every time it is shown.

    I really wouldn't blindly add an item in onPrepareOptionsMenu ever. You should check if it's already been added first.