Android - Correct use of invalidateOptionsMenu()
invalidateOptionsMenu()
is used to say Android, that contents of menu have changed, and menu should be redrawn. For example, you click a button which adds another menu item at runtime, or hides menu items group. In this case you should call invalidateOptionsMenu()
, so that the system could redraw it on UI. This method is a signal for OS to call onPrepareOptionsMenu()
, where you implement necessary menu manipulations.
Furthermore, OnCreateOptionsMenu()
is called only once during activity (fragment) creation, thus runtime menu changes cannot be handled by this method.
All can be found in documentation:
After the system calls onCreateOptionsMenu(), it retains an instance of the Menu you populate and will not call onCreateOptionsMenu() again unless the menu is invalidated for some reason. However, you should use onCreateOptionsMenu() only to create the initial menu state and not to make changes during the activity lifecycle.
If you want to modify the options menu based on events that occur during the activity lifecycle, you can do so in the onPrepareOptionsMenu() method. This method passes you the Menu object as it currently exists so you can modify it, such as add, remove, or disable items. (Fragments also provide an onPrepareOptionsMenu() callback.)
On Android 2.3.x and lower, the system calls onPrepareOptionsMenu() each time the user opens the options menu (presses the Menu button).
On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the action bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().
use this to reload new menu during app lifecycle:
new:
getActivity().invalidateOptionsMenu();
old
ActivityCompat.invalidateOptionsMenu(getActivity());
You need to override method onPrepareOptionsMenu()
, write your update code of action menu in same method and if you are using fragment then add setHasOptionsMenu(true);
in onCreateView()
.
Hope it helps you
One use I've found is forcing an order of operations between onResume
and onCreateOptionsMenu/onPrepareOptionsMenu
. The natural order (as of platform 22 at least) seems to flip flop around, especially when re-orientating your device.
Call invalidateOptionsMenu
() in onResume
() and you'll guarantee that onPrepareOptionsMenu
will be called after onResume (it may additionally be called before). For example, this will allow enabling a menu item based on data retrieved in onResume
.