问题
I am a newbie to android when I am going through a sample code for navigation drawer I found he called the method invalidateOptionsMenu() so I searched regarding its functionality but couldn't find an answer so can anyone please brief me its functionality and whenshould we use that.
回答1:
This function tell android that it should redraw the menu. By default, once the menu is created, it won't be redrawn every frame (since that would be useless to redraw the same menu over and over again).
You should call this function when you changed something in the option menu (added an element, deleted an element or changed a text). This way android will know that it's time te redraw the menu and your change will appear.
Hope this answers your question
回答2:
I use this method in combination with actionbar: When I need to populate actionbar with new menu items, I call invalidateOptionsMenu(), then onCreateOptionsMenu is called and I can inflate menu that I need. :-)
for more info see http://developer.android.com/reference/android/app/Activity.html#invalidateOptionsMenu() or Change options menu during runtime - invalidateOptionsMenu()
回答3:
That would trigger another call to onCreateOptionsMenu where you can decide to display a new menu. It's basically the right way of replacing the current menu with a new one.
回答4:
When Activity is created then the onCreateOptionsMenu method is called. Inside you can inject menu from menu.xml ol build it by hand. But if you want to change this menu during activity life you must call invalidateOptionsMenu();
eg:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (something) {
// buildOneMenu
} else {
// buildAnotherMenu
}
}
...
something = true;
invalidateOptionsMenu();
回答5:
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.
来源:https://stackoverflow.com/questions/22374855/what-is-the-use-of-invalidateoptionsmenu-in-android