Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I hide a menu item in the actionbar?

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(); 
like image 207
Stir Zoltán Avatar asked May 21 '12 21:05

Stir Zoltán


People also ask

How do you make a menu item invisible?

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.

How do we hide the menu on the toolbar in one fragment?

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.


2 Answers

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

like image 188
K-ballo Avatar answered Oct 11 '22 02:10

K-ballo


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.

like image 40
P1r4nh4 Avatar answered Oct 11 '22 02:10

P1r4nh4