Home » Android » android – Dynamic control of action/menu items in ActionBar

android – Dynamic control of action/menu items in ActionBar

Posted by: admin June 15, 2020 Leave a comment

Questions:

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.

How to&Answers:

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();

Answer:

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();
    }