I using menu drawer which has more Fragment
s. In some Fragment
s I have menu item REFRESH but in some fragments I want hide this menu item (I don\'t
Just find the item you want to hide using findItem
then set its visibility to false
.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.action_settings);
item.setVisible(false);
}
I used the code below for hiding menu items in a fragment where I don't want to use it. Note: Please read comment
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
Fragment whichFragment=getVisibleFragment();//getVisible method return current visible fragment
String shareVisible=whichFragment.getClass().toString();
if(shareVisible.equals(AccFragment.class.toString())
||shareVisible.equals(SocFragment.class.toString())
||shareVisible.equals(DevFragment.class.toString())
){
MenuItem item=menu.findItem(R.id.action_share);
item.setVisible(false);
}
return super.onCreateOptionsMenu(menu);
}
There are many different versions of similar solutions but unfortunately, none of them worked for me. I am sharing what eventually was useful for me to hide the whole overflow menu with multiple menu items. Thought maybe it's useful for anyone.
I grouped my menus with an id
and then referred that id
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.setGroupVisible(R.id.menu_overflow, false);
super.onPrepareOptionsMenu(menu);
}
If you want to hide any individual menu item then you can use
menu.getItem(R.id.action_licenses).setVisible(false);
Important thing is that you should have setOptionsMenu(true)
in onViewCreated()
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
In Fragment Class
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
}
Call setHasOptionMenu(true)
in onCreateView()
and Do not call super.onCreateOptionsMenu()
in fragment's onCreateOptionMenu()
instead call menu.clear()
because this will override the existing menu with the activity's menu
This worked in my case.
In the fragment where you want to hide the Item
@Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item=menu.findItem(R.id.action_search);
if(item!=null)
item.setVisible(false);
}
and in onCreate() of your fragment
setHasOptionsMenu(true);