Search code examples
androidmenu

Changing options menu/actionbar menu programatically for 3.0+


In short, here's my question:

Can option menus (shown in the actionbar) be modified programatically on android 3.0+?

I have a wizard-style activity in which I use a ViewFlipper to switch between views, or steps.

The steps are: 1 -> 2 -> 3. Only the second screen (2) has a menu item, while the others don't. I have tried hanging on to the Menu reference (source) and either removing/adding items or just hiding/showing them.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    this.mMenu = menu;
    
    getMenuInflater().inflate(R.menu.my_menu, menu);
    mMenu.getItem(0).setVisible(false);
    
    return super.onCreateOptionsMenu(menu);
}

Switch to the second screen ->

public void showNext(View v) {
    if (mVFlipper.getDisplayedChild() < (mVFlipper.getChildCount() - 1)) {
        mVFlipper.showNext();
        if (mVFlipper.getDisplayedChild() == 1) {
            setTitle("Second screen");
            mMenu.getItem(0).setVisible(true);
        }
    }
}

This works fine on 2.2, but fails miserably on 4.1. Starting off with a visible MenuItem and hiding it later works. Starting off with an invisible menu item and showing it later -


Solution

  • There is a bug in Android's MenuItem setVisible that causes problems when turning items back to visible.

    In your onCreateOptionsMenu(), add a check to see if the displayed page needs the Menu, if it does, add the MenuItem. Then, call invalidateOptionsMenu() whenever the page changes. That will rebuild the Menu.