Artur Couto
Artur Couto

Reputation: 498

Icon setVisible duplicating menu

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?

Upvotes: 1

Views: 464

Answers (2)

jenzz
jenzz

Reputation: 7269

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:

private boolean showRefresh;
private boolean showBack;

Override the onPrepareOptionsMenu() method and set the menu item's visbility depending on the respective boolean:

@Override
public boolean onPrepareOptionsMenu( Menu menu ) {

    super.onPrepareOptionsMenu( menu );

    menu.findItem( R.id.refresh ).setVisible( showRefresh );
    menu.findItem( R.id.back ).setVisible( showBack );

    return true;
}

No every time you want to change the visibility of a certain menu item, set the respective boolean accordingly and call the invalidateOptionsMenu() method.

Upvotes: 1

Gabriele Mariotti
Gabriele Mariotti

Reputation: 364361

You can read this.

Changing menu items at runtime

Once the activity is created, the onCreateOptionsMenu() method is called only once, as described above. The system keeps and re-uses the Menu you define in this method until your activity is destroyed. If you want to change the Options Menu any time after it's first created, you must override the onPrepareOptionsMenu() method. This passes you the Menu object as it currently exists. This is useful if you'd like to remove, add, disable, or enable menu items depending on the current state of your application.

E.g.

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
     super.onPrepareOptionsMenu(menu);
     MenuItem item = menu.findItem(R.id.refresh);
     item.setVisible(false);
     return true;
}

Upvotes: 1

Related Questions