Reputation: 167
I'm looking to hide a icons from the ActionBar depending on variables. Is there a simple way to do this?
Will I need to use onPrepareOptionsMenu()
and if so how?
Upvotes: 1
Views: 113
Reputation: 2506
To hide menu items you should use the setVisible()
method on your menu item inside your activity onPrepareOptionsMenu()
override after your menu has been inflated. For example:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.example, menu);
if(showItem) {
menu.findItem(R.id.icon).setVisible(true);
} else {
menu.findItem(R.id.icon).setVisible(false);
}
return true;
}
If you have declared your variable inside onCreate()
, it will be limited to the scope of onCreate()
and therefore inaccessible inside onPrepareOptionsMenu()
.
For example, instead of this:
@Override
protected void onCreate(Bundle savedInstanceState) {
boolean showItem = false;
// ...
}
Declare it like this:
public boolean showItem = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
}
Also if you want to change the visibility on button press for example, you will need to call the invalidateOptionsMenu()
method to reload the menu.
Upvotes: 2
Reputation: 17085
You need to call invalidateOptionsMenu()
depending on your variable.
When you call invalidateOptionsMenu()
the onPrepareOptionsMenu
will be called , where you can hide/show the option menu like this..
@Override
public boolean onPrepareOptionsMenu(Menu menu){
for(int index = 0 ; index < menu.size() ; index ++){
MenuItem menuItem = menu.getItem(index);
if(menuItem != null) {
// hide the menu items
menuItem.setVisible(false);
}
}
return super.onPrepareOptionsMenu(menu);
}
Upvotes: 0