onPrepareOptionsMenu Duplicates item in ActionBar

2019-04-11 01:30发布

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

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-11 02:22

onPrepareOptionsMenu is called every time before menu is shown.

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

查看更多
Lonely孤独者°
3楼-- · 2019-04-11 02:23

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.

查看更多
疯言疯语
4楼-- · 2019-04-11 02:24

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.

查看更多
登录 后发表回答