Show different menu options on Toolbar for activity and fragment

一个人想着一个人 提交于 2019-12-04 03:28:21

I'm not sure if you can do this with onCreateOptionsMenu(). I think your better bet will be onPrepareOptionsMenu().

You can force Android to refresh the options menu by simply writing getActivity().invalidateOptionsMenu() in Fragment's onResume().

So your onPrepareOptionsMenu() will look like:

@Override
public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    menu.clear();    //remove all items
    getActivity().getMenuInflater().inflate(R.menu.menu_fragment, menu);
}

Store the menu reference in a variable.

 private Menu menu;

       @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.main, menu);
            this.menu = menu;
            return super.onCreateOptionsMenu(menu);
        }

When replacing to mentioned fragment do the following.

private void hideOption(int id) {
        menu.findItem(id).setVisible(false);
    }

Call hideOption() with menu id. for ex,

hideOption(R.id.action_search);

And vice versa for showing.or follow suggestion of #Droidwala

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