user742030
user742030

Reputation:

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

Upvotes: 3

Views: 5582

Answers (4)

Temur Isroilov
Temur Isroilov

Reputation: 596

Cheking menu size before inflating it worked for me

override fun onPrepareOptionsMenu(menu: Menu) {
    super.onPrepareOptionsMenu(menu)
    if (menu.size == 0) {
        activity?.menuInflater?.inflate(R.menu.menu_filter, menu)
    }
    // ...
}

Upvotes: 0

Akah
Akah

Reputation: 1398

I use fragments within an activity and i use swipe to switch between them. My main activity has some menu items, but i use my fragment to dynamically add one at runtime, i.e when the fragment becomes visible. My fragament's oncreateOptions method is as shown below: The menu item appears now only once

  @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        //menu.clear();
        if(menu.size() == 1) {
            // inflater.inflate(R.menu.dashboard_main,menu);
            MenuItem mit = menu.add("Refresh");
            mit.setIcon(android.R.drawable.stat_notify_sync);
            mit.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        }
    }

Another possible fix is that you could add fragments to your activity only when the instancestate bundle is null, because by then, your activity would have discarded the fragment and as such , it is necessary for it to be recreated with its menu items.

Upvotes: -1

lynn8570
lynn8570

Reputation: 1683

onPrepareOptionsMenu is called every time before menu is shown.

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

Upvotes: 15

kabuko
kabuko

Reputation: 36302

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.

Upvotes: 4

Related Questions