Tag Archives: findItem

Android menuItem invisible set to visible

Let’s say we have 2 menu items in a menu, one of which is visible and the other not.

So in /res/menu/main_menu.xml we have:

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

    <item
        android:id="@+id/menu_1"
        android:title="@string/menu_1"
        android:visible="true"
        />
    <item
        android:id="@+id/menu_2"
        android:title="@string/menu_2"
        android:visible="false"
        />

</menu>

This is all good and we will see the first item but not the second.
What happens if at some moment we need to make the second item visible. We naturally try

this.findViewById(R.id.menu_2).setVisibility(View.VISIBLE);

which will fail due to null pointer. However

this.findViewById(R.id.menu_1).setVisibility(View.GONE);

Will work.
This is because menuItem 2 has never been generated as a view and thus never found.
Note that menu items can be visible or invisible(gone) no middle option as with the views.

So to set a menuitem visible we need:
1) save the menu instance from “onCreateOptionsMenu” callback:

        Menu currentMenu;
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		currentMenu = menu;
		return true;
	}

2) use this instance to find the Menu Item and set it visible

currentMenu.findItem(R.id.menu_2).setVisible(true);