onPrepareOptionsMenu Duplicates item in ActionBar

旧巷老猫 提交于 2019-12-21 21:27:55

问题


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


回答1:


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.




回答2:


onPrepareOptionsMenu is called every time before menu is shown.

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




回答3:


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.



来源:https://stackoverflow.com/questions/9491800/onprepareoptionsmenu-duplicates-item-in-actionbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!