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();
The best way to hide all items in a menu with just one command is to use "group" on your menu xml. Just add all menu items that will be in your overflow menu inside the same group. Then, on your activity (preferable at onCreateOptionsMenu), use command setGroupVisible to set all menu items visibility to false or true.
This is because of the menu item's android:orderInCategory attribute value. When you click the hide button to hide the fragment. The fragment menu items disappear from the action bar also. You can also click back menu to exit the fragment and the activity.
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 state invalidateOptionsMenu(); // now onCreateOptionsMenu(...) is called again ... @Override public 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With