How can I get the options menu of my Activity?
Be wary of invalidateOptionsMenu()
. It recreates the entire menu. This has a lot of overhead and will reset embedded components like the SearchView
. It took me quite a while to track down why my SearchView
would "randomly" close.
I ended up capturing the menu as posted by Dark and then call onPrepareOptionsMenu(Menu)
as necessary. This met my requirement without an nasty side effects. Gotcha: Make sure to do a null check in case you call onPrepareOptionsMenu()
before the menu is created. I did this as below:
private Menu mOptionsMenu;
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
mOptionsMenu = menu
...
}
private void updateOptionsMenu() {
if (mOptionsMenu != null) {
onPrepareOptionsMenu(mOptionsMenu);
}
}
Call invalidateOptionsMenu() instead of passing menu object around.