Fragments, with the same menu, on the same layout cause duplicated menuitem

此生再无相见时 提交于 2019-12-02 23:33:07

I've found the not-so-good solution. In onCreateOptionsMenu() of each fragment, call menu.clear() to remove any existing menu item before inflate the menu.

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.clear();
    inflater.inflate(R.menu.main, menu);
    super.onCreateOptionsMenu(menu, inflater);

}

This would post the future problems. I may decide to uses different menus for each fragments, which each menus share menu items. I think we can manipulate the menu at the onCreateOptionsMenu(), but currently I don't know how to get the menu item associated with the fragment before inflate it with MenuInflater.

I'm late but maybe it can help others. This sounds like a design smell (if this term exists).

If both fragments have same menu items, and it doesn't matter which fragment's items are used (that is, it makes no difference if you click item 1 of fragment A, or item 1 of fragment B), then probably the menu should not be part of the fragment, but of the activity. That would solve the duplication.

do you call the super method of createOptionMenu?

  • then it can happens that alls optionmenus are shown.

I found a work around, that it working for me. In onOptionsItemSelected method, first i do its check if the class its equal to or not to the class i get from the fragmentManager with findFragmentById(R.id.content_frame).getClass()

I got something like this

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {        
        if( this.class !=  getFragmentManager().findFragmentById(R.id.content_frame).getClass() ) {
            return false; //  must do nothing
        }
        // do your menu stuff
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!