Set visibility in Menu programmatically android

Solution 1:

Put this method in your Activity

public boolean onPrepareOptionsMenu(Menu menu)
{
    MenuItem register = menu.findItem(R.id.menuregistrar);      
    if(userRegistered) 
    {           
        register.setVisible(false);
    }
    else
    {
        register.setVisible(true);
    }
    return true;
}

in shorter version you could write:

MenuItem register = menu.findItem(R.id.menuregistrar);      
register.setVisible(!userRegistered);  //userRegistered is boolean, pointing if the user has registered or not.
return true;

Solution 2:

I would simplify Adil's solution even further with the following:

public boolean onPrepareOptionsMenu(Menu menu)
{
    MenuItem registrar = menu.findItem(R.id.menuregistrar);      
    registrar.setVisible(!isRegistered);
    return true;
}

Solution 3:

Menu Object has a property to set the visibility of a menu's item using setVisible(boolean)//

Example

private Menu menu_change_language;
...

...

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    ...
    ...
    menu_change_language = menu;
    ...
    ...

    return super.onCreateOptionsMenu(menu);
}

use code below for hiding Menu Item:

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

Solution 4:

Use public boolean onPrepareOptionsMenu (Menu menu) it is called everytime you press the menu button and do your stuff there. or use your oncreateoptionsmenu() in different activities to inflate different menus - this one is called only once.

Cheers

Solution 5:

If you want to change the visibility inside the onOptionsItemSelected whenever you click the menu

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   item.setVisible(true);
   return true;
}

OR for item in the menu that you didn't click on

private Menu globalMenuItem;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
   getMenuInflater().inflate(R.menu."menu Xml Name", menu);
   globalMenuItem = menu;
   return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
   globalMenuItem.findItem(R.id."id of the menu item").setVisible(true);
   return true;
}