I have been searching a lot on invalidateOptionsMenu()
and I know what it does. But I cannot think of any real life example where this method could be useful.
I mean, for instance, let's say we want to add a new MenuItem
to our ActionBar
, we can simply get the Menu from onCreateOptionsMenu(Menu menu)
and use it in any button's action.
Now to my real question, is following the only way of using invalidateOptionsMenu()
?
bool _OtherMenu;
protected override void OnCreate (Bundle bundle)
{
_OtherMenu = false;
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate
{
if(_OtherMenu)
_OtherMenu = false;
else
_OtherMenu = true;
InvalidateOptionsMenu ();
};
}
public override bool OnCreateOptionsMenu (IMenu menu)
{
var inflater = this.SupportMenuInflater;
if(_OtherMenu)
inflater.Inflate (Resource.Menu.another_menu, menu);
else
inflater.Inflate (Resource.Menu.main_activity_menu, menu);
return base.OnCreateOptionsMenu (menu);
}
Click the button and a different menu appears. Click the button again and previous menu appears.
P.S. Sorry for the C# syntax.
use this to reload new menu during app lifecycle:
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 callinvalidateOptionsMenu()
, so that the system could redraw it on UI. This method is a signal for OS to callonPrepareOptionsMenu()
, 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:
One use I've found is forcing an order of operations between
onResume
andonCreateOptionsMenu/onPrepareOptionsMenu
. The natural order (as of platform 22 at least) seems to flip flop around, especially when re-orientating your device.Call
invalidateOptionsMenu
() inonResume
() and you'll guarantee thatonPrepareOptionsMenu
will be called after onResume (it may additionally be called before). For example, this will allow enabling a menu item based on data retrieved inonResume
.The best way that worked for me is demonstrated below
Put the initial state of the menu in onCreateOptionsMenu(...)
Use the invalidateOptionsMenu() to force onCreateOptionsMenu(...) and onPrepareOptionsMenu(...)
In onPrepareOptionsMenu(...), call menu.clear() to remove all items from the menu.
Still in onPrepareOptionsMenu(...) place your dynamic menu changes after the clear
Hope this helps...
XML menu sample:
Code inside a sample fragment:
You need to override method
onPrepareOptionsMenu()
, write your update code of action menu in same method and if you are using fragment then addsetHasOptionsMenu(true);
inonCreateView()
.Hope it helps you