Using onPrepareOptionsMenu instead of onCreateOptionsMenu in fragment

I had a problem setting some of the fragment menu items in an ActionBar , and I found a way to solve it, but I don’t understand why this worked.

I wanted to change the visibility of the menu item right after I puffed it from the XML menu file into onCreateOptionsMenu . The code seems to work fine, but there is no visible effect. I solved the problem of inflating the menu in onCreateOptionsMenu , but changing its visibility in the onPrepareOptionsMenu method.

I want to know why changing visibility in onCreateOptionsMenu does not work.

What can I do in onPrepareOptionsMenu , which I cannot do in onCreateOptionsMenu ?

Is there any template?

Thanks!

Here's the appropriate code, just in case:

 public class MyFragment extends Fragment { @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.my_menu, menu); // This does not work, compiles and runs fine, but has no visible effect MenuItem someMenuItem = menu.findItem(R.id.some_menu_item); someMenuItem.setVisible(false); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); // This does work MenuItem someMenuItem = menu.findItem(R.id.some_menu_item); someMenuItem.setVisible(false); } } 
+7
source share
4 answers

You should call super.onCreateOptionsMenu(menu, inflater); after creating your menu, not before. This sends the menu up the hierarchy and other fragments, or the activity may want to add items on its own.

The activity is responsible for displaying and managing the menu, so if you change the visibility after it has been put into action, nothing will happen.

Now when you call super.onPrepareOptionsMenu(menu); , it will β€œcook” this menu, but now it will make the changes you made to onCreateOptionsMenu .

+5
source

Maybe the code should return true in order to make the menu visible, this means that you should put return true; in both onCreateOptionsMenu() and onPrepareOptionsMenu() .

Hope this helps.

0
source

I use onPrepareOptionsMenu to update which items in the menu should be active and which of them should be highlighted / deleted depending on the current state of activity. Use the setVisible method of a menu item to control whether it is currently displayed in the menu or not.

0
source

It works for me

 public class ContentFragment extends android.support.v4.app.Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.content_frame,container,false); setHasOptionsMenu(true); return v; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.note_menu,menu); super.onCreateOptionsMenu(menu, inflater); } } 

Try

-2
source

All Articles