Android – onPrepareOptionsMenu Duplicates item in ActionBar

androidandroid-actionbarandroid-fragmentsmenuitem

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

Best Answer

onPrepareOptionsMenu is called every time before menu is shown.

Use menu.clear() in onPrepareOptionsMenu(), and then add new menu item.