Tag Archives: menuitem

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" >



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


which will fail due to null pointer. However


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


Android menu item set onClick method from xml

There is a simple and easy way to set the callback method for a view from the xml describing the view.

We simply need to add to our view:


And then in the code implement the “doTheClick” method.

public void doTheClick(View v) {    	
		//do smth here

To do this for a menuItem you just need to change the “doTheClick” so it accepts MenuItem argument.

public void doTheClick(MenuItem mi) {    	
		//do smth here