I have a menu item and I want to change its visibility programmatically. The menu is this
Since you did not provide any other code, I can't say much about it.
However, whenever you want to change the menu, you should call invalidateOptionsMenu(). What that does is it invalidates the menu, which in turn forces it to be recreated. During its recreation, one of the callbacks is onPrepareOptionsMenu(Menu menu). This is where you can make the change to your menu.
Example:
// This is where I want to change the menu. Can be anywhere in your activity.
invalidateOptionsMenu();
Then override this method
// Override this method to do what you want when the menu is recreated
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.pencil).setVisible(false);
return super.onPrepareOptionsMenu(menu);
}
The way to access the menu through the toolbar, and no need to dedicate variable:
MenuItem menuItem = ((Toolbar)findViewById(R.id.toolbar)).getMenu().findItem(R.id.pencil);
menuItem.setVisible(true);