8

Is there a way to dynamically disable , hide, add/remove menu items in ActionBar ? For example, an action is disabled until user fills a valid phone number in an activity.

I didn't find any useful methods in ActionBar API, the only way seems to be using a custom View in ActionBar.

S.D.
  • 29,290
  • 3
  • 79
  • 130

2 Answers2

20

To tell ActionBar to refresh its menu items: invalidateOptionsMenu()

then to enable/disable Menu Items:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem item= menu.findItem(R.id.men_1);
    //depending on your conditions, either enable/disable
    item.setEnabled(false);
    super.onPrepareOptionsMenu(menu);
    return true;
}

and to hide the action bar you have:

getActionBar().hide();
Archie.bpgc
  • 23,812
  • 38
  • 150
  • 226
  • 1
    `onPrepareOptionsMenu` must return `boolean` value ,you must return true for the menu to be displayed; if you return false it will not be shown. – Mickey Tin Feb 07 '13 at 16:01
  • 7
    If you are using the the support library and `ActionBarActivity` you will need to use [`supportInvalidateOptionsMenu()`](http://developer.android.com/reference/android/support/v7/app/ActionBarActivity.html#supportInvalidateOptionsMenu%28%29) – IT-Dan Aug 30 '13 at 14:28
0

Another option: having a field in the Activity storing the Menu. This way it's possible to call getMenuInflater().inflate() and menu.clear() from anywhere you want in this activity

So, it looks something like this:

class MyActivity extends ActionBarActivity {

    Menu actionBar;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        actionBar = menu;
        return true;
    }

    //Possible usage
    void showActionBar1 () {
        getMenuInflater().inflate(R.menu.menu_1, actionBar);
        actionBar.findItem(R.id.menu_1_btn_1).setOnMenuItemClickListener();
    }

    void showActionBar2 () {
        getMenuInflater().inflate(R.menu.menu_2, actionBar);
        ...
    }

    void clearActionBar () {
        if (actionBar != null) actionBar.clear();
    }
Alex
  • 1,165
  • 2
  • 9
  • 27