By default I set the visibility to false by using following code.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_items, menu);
menu.findItem(R.id.action_share).setVisible(false);
return true;
}
Now how can I make it visible again when user clicks a button in my activity.
If you want to hide Action Bar from the entire application (from all Activities and fragments), then you can use this method. Just go to res -> values -> styles. xml and change the base application to “Theme. AppCompat.
Call invalidateOptionsMenu() when you want to hide the option.
If you've developed for Android 3.0 and higher, the system calls onCreateOptionsMenu() when starting the activity, in order to show items to the app bar.
In your onCreateOptionsMenu:
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_items, menu);
if (hideIcon){
menu.findItem(R.id.action_share).setVisible(false);
}else{
menu.findItem(R.id.action_share).setVisible(true);
}
return true;
}
In method where you want to show/hide the icon, just set the boolean hideIcon to true or false and call :
invalidateOptionsMenu();
to refresh the menu.
get the instance of that menu item, and you can set its item Visibility every time.
Menu mMenu;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_items, menu);
mMenu = menu;
mMenu.findItem(R.id.action_share).setVisible(false);
return true;
}
//somewhere else
mMenu.findItem(R.id.action_share).setVisible(true);
and based on @chol answer call invalidateOptionsMenu();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With