In my action bar I have 2 menu items:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/refresh"
android:title="Refresh"
android:icon="@drawable/refresh"
android:showAsAction="ifRoom" >
</item>
<item android:id="@+id/back"
android:title="Back"
android:icon="@drawable/back"
android:showAsAction="ifRoom" >
</item>
</menu>
I’m trying to turn “invisible” my menu item “Refresh”, when I call the function refreshinvisible(), the Refresh item goes away, but now the action bar shows two “back” items… Why? (I’m using SherlockActionBar)
My refreshinvisible() function:
public void refreshinvisible(){
MenuItem item = menu.findItem(R.id.refresh);
item.setVisible(false);
}
Anyone know how to proceed?
There is a method called onPrepareOptionsMenu() which is called every time right before the menu is shown, i.e. before onCreateOptionsMenu() is called. You can use the activity’s invalidateOptionsMenu() method to trigger a redraw of the options menu.
Hence, you can easily re-create your menu taking into account certain conditions.
Here’s some code. Define two booleans as fields of your class, for example:
Override the
onPrepareOptionsMenu()method and set the menu item’s visbility depending on the respectiveboolean:No every time you want to change the visibility of a certain menu item, set the respective
booleanaccordingly and call theinvalidateOptionsMenu()method.