How do I hide a menu item in the actionbar?
Get a MenuItem
pointing to such item, call setVisible
on it to adjust its visibility and then call invalidateOptionsMenu()
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 returns null
for item
and that's causing the crash. What you need instead is to do:
MenuItem item = menu.findItem(R.id.addAction);
Here is the sequence in which you should call:first call invalidateOptionsMenu()
and then inside onCreateOptionsMenu(Menu)
obtain a reference to the MenuItem (by calling menu.findItem()
) and call setVisible()
on it
Found an addendum to this question:
If you want to change the visibility of your menu items on the go you just need to set a member variable in your activity to remember that you want to hide the menu and call invalidateOptionsMenu()
and hide the items in your overridden onCreateOptionsMenu(...)
method.
//anywhere in your code...mState = HIDE_MENU; // setting stateinvalidateOptionsMenu(); // now onCreateOptionsMenu(...) is called again...@Overridepublic boolean onCreateOptionsMenu(Menu menu){ // inflate menu from xml MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.settings, menu); if (mState == HIDE_MENU) { for (int i = 0; i < menu.size(); i++) menu.getItem(i).setVisible(false); }}
In my example I've hidden all items.
Yes.
- You can set a flag/condition.
- Call
invalidateOptionsMenu()
when you want to hide the option. This will callonCreateOptionsMenu()
. - In
onCreateOptionsMenu()
, check for the flag/condition and show orhide it the following way:
MenuItem item = menu.findItem(R.id.menu_Done);if (flag/condition)) { item.setVisible(false); } else { }