How can I set the visibility of an ActionBar item in different fragment

ⅰ亾dé卋堺 提交于 2019-11-30 13:54:25

You should try this in your Fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // ...  
    // call the method setHasOptionsMenu, to have access to the menu from your fragment
    setHasOptionsMenu(true);

    //...
}

// the create options menu with a MenuInflater to have the menu from your fragment
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.findItem(R.id.button_generator).setVisible(true);
    super.onCreateOptionsMenu(menu, inflater);
}  

And this, in your Activity:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getSupportMenuInflater().inflate(R.menu.my_layout, menu);
    menu.findItem(R.id.button_generator).setVisible(false);
    return true;
}

Hope this helps.

when you want to change fragment you will need to set a flag indicating what menu you want inflated then all you have to do is call invalidateOptionsMenu() in your activity to call onCreateOptonsMenu again and using your flag you set you inflate a different menu

I found a trick, you might wanna try this.

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