How can I change Action Bar actions dynamically?

AndroidAndroid Actionbar

Android Problem Overview


I have an Activity with ActionBar and tab navigation. I am using the split mode, so the tabs are at the top and actions are in the bottom bar. How can I dynamically change the bottom actions? I need this because every tab has different actions.

Android Solutions


Solution 1 - Android

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.

Solution 2 - Android

Activity.invalidateOptionsMenu() requires API Level 11. There is a simpler solution which is backwards compatible:

Add the MenuItem to the Menu initially but set its visibility to false. Set visibility to true when desired, using MenuItem.setVisible()

Solution 3 - Android

ActionMode.invalidate() did the trick. It caused the onPrepareActionMode() to be invoked again.

Activity#invalidateOptionsMenu() did not cause the onPrepareActionMode() to be invoked when using list items with multi-select.

Solution 4 - Android

Activity.invalidateOptionsMenu() requires API Level 11. Use the Support library version of it supportInvalidateOptionsMenu().

AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.supportInvalidateOptionsMenu();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfhuchoView Question on Stackoverflow
Solution 1 - AndroidadampView Answer on Stackoverflow
Solution 2 - AndroidwoodlyView Answer on Stackoverflow
Solution 3 - AndroidAlikElzin-kilakaView Answer on Stackoverflow
Solution 4 - AndroidAhmed HegazyView Answer on Stackoverflow