I have an action bar with a menuitem. How can I hide/show that menu item?
This is what I'm trying to do:
MenuItem item = (MenuItem) findViewById(R.id.addAction);
item.setVisible(false);
this.invalidateOptionsMenu();
I have an action bar with a menuitem. How can I hide/show that menu item?
This is what I'm trying to do:
MenuItem item = (MenuItem) findViewById(R.id.addAction);
item.setVisible(false);
this.invalidateOptionsMenu();
For those using the Appcompat library: If your Activity subclasses ActionBarActivity, you can call supportInvalidateOptionsMenu()
Seen here: https://stackoverflow.com/a/19649877/1562524
This Approach worked for me:
By setting the Visibility of all items in Menu, the appbar menu or overflow menu will be Hide automatically
Example
...
...
Before going to other fragment use bellow code:
This worked for me from both Activity and Fragment
P1r4nh4 answer works fine, I just simplified it using a boolean flag:
Get a
MenuItem
pointing to such item, callsetVisible
on it to adjust its visibility and then callinvalidateOptionsMenu()
on your activity so the ActionBar menu is adjusted accordingly.Update: A
MenuItem
is not a regular view that's part of your layout. Its something special, completely different. Your code returnsnull
foritem
and that's causing the crash. What you need instead is to do:Here is the sequence in which you should call: first call
invalidateOptionsMenu()
and then insideonCreateOptionsMenu(Menu)
obtain a reference to the MenuItem (by callingmenu.findItem()
) and callsetVisible()
on it