How can I force the onPrepareOptionsMenu method to fire?

Mridang Agarwalla picture Mridang Agarwalla · Sep 13, 2012 · Viewed 7k times · Source

In my activity's onCreateOptionsMenu method, I am simply inflating my menu layout file and attaching it.

I want to show/hide some menu items based on a value a of a global variable, I do this in the onPrepareOptionsMenu method. I've read that this is the correct place to do it.

My onPrepareOptionsMenu method doesn't always fire. I don't know why but it doesn't always fire when I press the "Menu" button on my phone. Maybe it has some thing to do with it's internal state.

It seems to fire when the Acitvity is being created. Pressing the "Menu" button for the first time, doesn't cause it to fire but if I press the menu button a second time, it works just fine.

Is there a way I could force the onPrepareOptionsMenu to fire.

Thanks


Smok suggested using the invalidateOptionsMenu method to invalidate the menu items but this causes the onCreateOptionsMenu method to fire too. Here's my method:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    System.out.println("onCreate");

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search, menu);

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setIconified(false);
    searchView.requestFocusFromTouch();

    return true;

}

@Override
public boolean onPrepareOptionsMenu (Menu menu) {
    System.out.println("prepared");

    if (this.objAdapter == null) {
        menu.findItem(R.id.sort).setVisible(false);
        menu.findItem(R.id.filter).setVisible(false);
        menu.findItem(R.id.group).setVisible(false);
    } else {
        menu.findItem(R.id.sort).setVisible(true);
        menu.findItem(R.id.filter).setVisible(true);
        menu.findItem(R.id.group).setVisible(true);

    }

    return true;
}

As you can see from my onCreateOptionsMenu method, invoking it again will cause the focus to be lost to the SearchView.

Answer

Mridang Agarwalla picture Mridang Agarwalla · Sep 13, 2012

As Smok pointed out: by calling invalidateOptionsMenu().