varunkr varunkr - 1 month ago 11
Android Question

MenuItem hidden in fragment not visible when doing setVisible(true) in main activity

I have been stuck on this issue for quite a while now. In my code I have a fragment inside which I do not want to show the search menu item. To achieve that I do this inside the fragment

Inside

onCreate


setHasOptionsMenu(true);


Then

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
this.menu = menu;
MenuItem search = menu.findItem(R.id.action_search);
search.setVisible(false);
}


This works exactly as expected and hides the item. Now when i do back press the o
nBackPressed()
of the main activity is called and there I do this

@Override
public void onBackPressed() {

// code skipped
invalidateOptionsMenu();
}


This calls the
onCreateOptionsMenu
inside the main activity which is as follows

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);

item = menu.findItem(R.id.action_search);
item.setVisible(true);

//code skipped
}


The
onCreateOptionsMenu
function is called but unfortunately the
menuItem
still remains hidden, and I can't see the search menu.

Can someone please help, what might be the issue? Thanks in advance !!

Answer

The method onCreateOptionsMenu is only called when the activity is created (or the fragment). Use onPrepareOptionsMenu to set the visibility of the menu item. The invalidateOptionsMenu calls onPrepareOptionsMenu, not onCreateOptionsMenu.