user2269937 user2269937 - 22 days ago 9
Android Question

Disable Action Bar button in Android

Is it possible to disable a button in Action Bar in Android? I was looking around and I could not find any code snippet for that, I was thinking that there should be some easy way.

Answer
  1. Once you perform the user action when you want to disable the action bar, set some flag, say disableButtonFlag.

  2. Call invalidateOptionsMenu(). This will trigger onCreateOptionsMenu to be invoked to regenerate your menu.

  3. Finally modify your onCreateOptionsMenu to disable the button you want depending on the state of disableButtonFlag.

    if (disableButtonFlag) {
        menu.findItem(R.id.your_item).setEnabled(false);
    } else {
        menu.findItem(R.id.your_item).setEnabled(true);
    }
    

    Or more simply:

    menu.findItem(R.id.your_item).setEnabled(!disableButtonFlag);