How can I change Action Bar actions dynamically?

Since the actions are populated by the activity’s options menu you can use Activity#invalidateOptionsMenu(). This will dump the current menu and call your activity’s onCreateOptionsMenu/onPrepareOptionsMenu methods again to rebuild it.

If you’re using action bar tabs to change your fragment configuration there’s a better way. Have each fragment manage its own portion of the menu. These fragments should call setHasOptionsMenu(true). When fragments that have options menu items are added or removed the system will automatically invalidate the options menu and call to each fragment’s onCreateOptionsMenu/onPrepareOptionsMenu methods in addition to the activity’s. This way each fragment can manage its own items and you don’t need to worry about performing menu switching by hand.

Leave a Comment