How do I hide a menu item in the actionbar?

AndroidAndroid ActionbarMenuitemAndroid Menu

Android Problem Overview


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();

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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.

Solution 3 - Android

Yes.

  1. You can set a flag/condition.
  2. Call invalidateOptionsMenu() when you want to hide the option. This will call onCreateOptionsMenu().
  3. In onCreateOptionsMenu(), check for the flag/condition and show or hide it the following way:

> MenuItem item = menu.findItem(R.id.menu_Done); >
> if (flag/condition)) { > item.setVisible(false); > } else { }

Solution 4 - Android

You can call this:

MenuItem item = menu.findItem(R.id.my_item);
item.setVisible(false);

Update:

Make sure your code doesn't returns null for item or it may crash the application.

Solution 5 - Android

I was looking for an answer with a little more context. Now that I have figured it out, I will add that answer.

#Hide button by default in menu xml

By default the share button will be hidden, as set by android:visible="false".

enter image description here

main_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    
    <!-- hide share button by default -->
    <item
        android:id="@+id/menu_action_share"
        android:icon="@drawable/ic_share_white_24dp"
        android:visible="false"     
        android:title="Share"
        app:showAsAction="always"/>

    <item
        android:id="@+id/menu_action_settings"
        android:icon="@drawable/ic_settings_white_24dp"
        android:title="Setting"
        app:showAsAction="ifRoom"/>

</menu>

#Show button in code

But the share button can optionally be shown based on some condition.

enter image description here

MainActivity.java

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
	MenuItem shareItem = menu.findItem(R.id.menu_action_share);

    // show the button when some condition is true
    if (someCondition) {        
	    shareItem.setVisible(true);
    }

    return true;
}

#See also

Solution 6 - Android

didn't work for me. I had to explicitly use onPrepareOptionsMenu to set an item invisible.

So use onCreateOptionsMenu to create the menu and onPrepareOptionsMenu to change visibility etc.

Solution 7 - Android

Initially set the menu item visibility to false in the menu layout file as follows :

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:visible="false"
        android:id="@+id/action_do_something"
        android:title="@string/txt_do_something"
        app:showAsAction="always|withText"
        android:icon="@drawable/ic_done"/>
</menu>

You can then simply set the visibility of the menu item to false in your onCreateOptionsMenu() after inflating the menu.

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(menu,R.menu.menu);
    MenuItem item = menu.findItem(R.id.menuItemId);
    if (item != null){
        item.setVisible(false);
    }
}

Solution 8 - Android

Try this:

MenuItem myitem = menu.findItem(R.id.my_item);
myitem.setVisible(false);

Solution 9 - Android

This worked for me from both Activity and Fragment

@Override
public void onPrepareOptionsMenu(Menu menu) {
	super.onPrepareOptionsMenu(menu);
	if (menu.findItem(R.id.action_messages) != null)
		menu.findItem(R.id.action_messages).setVisible(false);
}

Solution 10 - Android

P1r4nh4 answer works fine, I just simplified it using a boolean flag:

public int mState = 0; //at the top of the code
//where you want to trigger the hide action
mState = 1; // to hide or mState = 0; to show
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 == 1) //1 is true, 0 is false
    {
        //hide only option 2
            menu.getItem(2).setVisible(false);
    }
}

Solution 11 - Android

According to Android Developer Official site,OnCreateOptionMenu(Menu menu) is not recomended for changing menu items or icons, visibility..etc at Runtime.

> After the system calls onCreateOptionsMenu(), it retains an instance of the Menu you populate and will not call onCreateOptionsMenu() again unless the menu is invalidated for some reason. However, you should use onCreateOptionsMenu() only to create the initial menu state and not to make changes during the activity lifecycle. > > If you want to modify the options menu based on events that occur during the activity lifecycle, you can do so in the onPrepareOptionsMenu() method. This method passes you the Menu object as it currently exists so you can modify it, such as add, remove, or disable items. (Fragments also provide an onPrepareOptionsMenu() callback.) --AndroidDeveloper Official Site --

As Recomended You can use this onOptionsItemSelected(MenuItem item) method track user inputs.

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.edit) {
        Intent intent = new Intent(this, ExampleActivity.class);
        intent.putExtra(BUNDLE_KEY, mConnection);
        startActivityForResult(intent, PICK_CHANGE_REQUEST);
        return true;
    } else if (id == R.id.delete) {
        showDialog(this);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

If you need to change Menu Items at Run time, You can use onPrepareOptionsMenu(Menu menu) to change them

@Override
public boolean onPrepareOptionsMenu(Menu menu){

    if (Utils.checkNetworkStatus(ExampleActivity.this)) {
        menu.findItem(R.id.edit).setVisible(true);
        menu.findItem(R.id.delete).setVisible(true);
    }else {
        menu.findItem(R.id.edit).setVisible(false);
        menu.findItem(R.id.delete).setVisible(false);
    }
    return true;
} 

Solution 12 - Android

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.

In this example we have two menu items that will always show (regular item and search) and three overflow items:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/someItemNotToHide1"
        android:title="ITEM"
        app:showAsAction="always" />

    <item
        android:id="@+id/someItemNotToHide2"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionViewClass="android.support.v7.widget.SearchView"
        android:title="Search"/>

    <group android:id="@+id/overFlowItemsToHide">
	<item android:id="@+id/someID" 
	android:orderInCategory="1" app:showAsAction="never" />
	<item android:id="@+id/someID2" 
	android:orderInCategory="1" app:showAsAction="never" />
	<item android:id="@+id/someID3" 
	android:orderInCategory="1" app:showAsAction="never" />
    </group>
</menu>

Then, on your activity (preferable at onCreateOptionsMenu), use command setGroupVisible to set all menu items visibility to false or true.

public boolean onCreateOptionsMenu(Menu menu) {
   menu.setGroupVisible(R.id.overFlowItems, false); // Or true to be visible
}

If you want to use this command anywhere else on your activity, be sure to save menu class to local, and always check if menu is null, because you can execute before createOptionsMenu:

Menu menu;

public boolean onCreateOptionsMenu(Menu menu) {
       this.menu = menu;
       
}

public void hideMenus() {
       if (menu != null) menu.setGroupVisible(R.id.overFlowItems, false); // Or true to be visible       
}

Solution 13 - Android

You can use toolbar.getMenu().clear(); to hide all the menu items at once

Solution 14 - Android

By setting the Visibility of all items in Menu, the appbar menu or overflow menu will be Hide automatically

Example

private Menu menu_change_language;

...

...

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    ...
    ...
    menu_change_language = menu;
    menu_change_language.findItem(R.id.menu_change_language)
           .setVisible(true);

    return super.onCreateOptionsMenu(menu);
}

Before going to other fragment use bellow code:

if(menu_change_language != null){                 
    menu_change_language.findItem(R.id.menu_change_language)
       .setVisible(false);
}

Solution 15 - Android

set a value to a variable and call invalidateOptionsMenu();

for example

    selectedid=arg2;
			invalidateOptionsMenu();


 public boolean onPrepareOptionsMenu(Menu menu) {
   
	if(selectedid==1){
		menu.findItem(R.id.action_setting).setVisible(false);
		menu.findItem(R.id.action_s2).setVisible(false);
		menu.findItem(R.id.action_s3).setVisible(false);
	}
	else{
		if(selectedid==2){
    		menu.findItem(R.id.action_search).setVisible(false);
    		menu.findItem(R.id.action_s4).setVisible(false);
    		menu.findItem(R.id.action_s5).setVisible(false);
    	}
	}
    return super.onPrepareOptionsMenu(menu);
}

Solution 16 - Android

https://stackoverflow.com/a/21215280/466363 - answered by Look Alterno and Sufian

  • ActivityCompat.invalidateOptionsMenu() doesn't callback onPrepareOptionsMenu(); it just update the menu directly.
  • My someMethod() get called from several places, even before onCreateOptionsMenu(), so I must check mMenu != null.
  • should work using API 8

.

private Menu mMenu;
   @Override
   public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
       inflater.inflate(R.menu.track_fragment, menu);
       mMenu = menu;
       }
   ...
   private void someMethod() {
   ...
       if (mMenu != null) {
          MenuItem item = mMenu.findItem(R.id.new_track);
          if (item != null) {
               item.setVisible(false);
               ActivityCompat.invalidateOptionsMenu(this.getActivity());
           }
       }
   ...
   }
  • ActivityCompat.invalidateOptionsMenu() doesn't callback onPrepareOptionsMenu(); it just update the menu directly.

  • My someMethod() get called from several places, even before onCreateOptionsMenu(), so I must check mMenu != null.

  • should work using API 8

Solution 17 - Android

If you did everything as in above answers, but a menu item is still visible, check that you reference to the unique resource. For instance, in onCreateOptionsMenu or onPrepareOptionsMenu

@Override
public void onPrepareOptionsMenu(Menu menu) {
	super.onPrepareOptionsMenu(menu);
	MenuItem menuOpen = menu.findItem(R.id.menu_open);
	menuOpen.setVisible(false);
}

Ctrl+Click R.id.menu_open and check that it exists only in one menu file. In case when this resource is already used anywhere and loaded in an activity, it will try to hide there.

Solution 18 - Android

> Android kotlin, hide or set visibility of a menu item in the action bar programmatically.

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    val inflater = menuInflater
    inflater.inflate(R.menu.main_menu, menu)
    val method = menu.findItem(R.id.menu_method)
    method.isVisible = false //if want to show set true
    return super.onCreateOptionsMenu(menu)
}

Solution 19 - Android

For those using the Appcompat library: If your Activity subclasses ActionBarActivity, you can call supportInvalidateOptionsMenu()

Seen here: https://stackoverflow.com/a/19649877/1562524

Solution 20 - Android

I think a better approach would be to use a member variable for the menu, initialize it in onCreateOptionsMenu() and just use setVisible() afterwards, without invalidating the options menu.

Solution 21 - Android

this code worked for me

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu,menu);
    if (Application.sharedPreferences.getInt("type",1) == 2)
    {
        menuItem = menu.findItem(R.id.menu_travel_orders);
        menuItem.setVisible(false);
    }
    return super.onCreateOptionsMenu(menu);
}

Solution 22 - Android

This Approach worked for me:

private  Menu thismenu;

if (condition)
{
   if(thismenu != null)
   {
       thismenu.findItem(R.id.menu_save).setVisible(true);
       Toast.makeText(ProfileActivity.this, 
    ""+thismenu.findItem(R.id.menu_save).getTitle(),
                Toast.LENGTH_SHORT).show();
   }else
   {
       thismenu.findItem(R.id.menu_save).setVisible(false);
   }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
   getMenuInflater().inflate(R.menu.profile_menu, menu);
   thismenu = menu;

   return true;
}

Solution 23 - Android

You are trying to access a menu item from an activity, which dont have the access to scope. The call to find the menu item will return null, because the view is not binded with neither the activity nor the layout you are calling from.

The menu items are binded with items such as "Navigation Bar" which in turn are binded with the corresponding activity.

So initialize those views in activity (), and then access the menu items withing that views.

Navigation navView;
navView = findViewById(R.id.navigationView);

MenuItem item = navView.getMenu().findItem(R.id.item_hosting);
item.setVisible(false);

Solution 24 - Android

use invalidateOptionsMenu()

in order to call onPrepareOptionsMenu(menu: Menu?)

> you should use onCreateOptionsMenu() only to create the initial menu state and not to make changes during the activity lifecycle... > > When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

https://developer.android.com/guide/topics/ui/menus

Solution 25 - Android

this works for me; I hope it helps you:

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
    getMenuInflater().inflate(R.menu.my_menu_setting, menu);

    for (int i = 0; i < menu.size(); i++){
        if(menu.getItem(i).getItemId() == R.id.this_item_i_want_to_hide){
            menu.getItem(i).setVisible(false);
        }
    }

    return true;
}

Solution 26 - Android

Create you menu options the normal way see code below and add a global reference within the class to the menu

Menu mMenu;  // global reference within the class
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_tcktdetails, menu);
    mMenu=menu;  // assign the menu to the new menu item you just created 
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_cancelticket) {
        cancelTicket();

        return true;
    }

    return super.onOptionsItemSelected(item);
}

Now you can toggle your menu by running this code with a button or within a function

if(mMenu != null) {
                mMenu.findItem(R.id.action_cancelticket).setVisible(false);
            }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStir Zolt&#225;nView Question on Stackoverflow
Solution 1 - AndroidK-balloView Answer on Stackoverflow
Solution 2 - AndroidP1r4nh4View Answer on Stackoverflow
Solution 3 - Androidsuhas_smView Answer on Stackoverflow
Solution 4 - AndroideliasView Answer on Stackoverflow
Solution 5 - AndroidSuragchView Answer on Stackoverflow
Solution 6 - AndroidhotzenView Answer on Stackoverflow
Solution 7 - AndroidAkhilaView Answer on Stackoverflow
Solution 8 - Androidmohamad sheikhiView Answer on Stackoverflow
Solution 9 - AndroidBala VishnuView Answer on Stackoverflow
Solution 10 - AndroidHiramView Answer on Stackoverflow
Solution 11 - AndroidChanaka FernandoView Answer on Stackoverflow
Solution 12 - AndroidAdriano MoutinhoView Answer on Stackoverflow
Solution 13 - AndroidAjeet YadavView Answer on Stackoverflow
Solution 14 - AndroidHantash NadeemView Answer on Stackoverflow
Solution 15 - AndroidzachariaView Answer on Stackoverflow
Solution 16 - AndroidShimon DoodkinView Answer on Stackoverflow
Solution 17 - AndroidCoolMindView Answer on Stackoverflow
Solution 18 - AndroidAftab AlamView Answer on Stackoverflow
Solution 19 - AndroidRuideraJView Answer on Stackoverflow
Solution 20 - AndroidCatalin ClabescuView Answer on Stackoverflow
Solution 21 - Androidsaigopi.meView Answer on Stackoverflow
Solution 22 - AndroidForest babaView Answer on Stackoverflow
Solution 23 - AndroidVeeyaaRView Answer on Stackoverflow
Solution 24 - AndroidDan AlboteanuView Answer on Stackoverflow
Solution 25 - AndroidCharles-QxView Answer on Stackoverflow
Solution 26 - AndroidClarence LunaloView Answer on Stackoverflow