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


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:

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

and to hide the action bar you have:



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;

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

    //Possible usage
    void showActionBar1 () {
        getMenuInflater().inflate(R.menu.menu_1, actionBar);

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

    void clearActionBar () {
        if (actionBar != null) actionBar.clear();