How To Call Or Control MenuItems From Fragment
Posted by blogmeister on
December 24, 2013
I thought that creating a custom method in my Activity class where I can change the visibility of a MenuItem and accessing it from the Fragment would work. Sadly, it did not.
It seems that the Fragment class has a method called setHasOptionsMenu(boolean) and you need to call that from within the onCreateView() method in order to be able to manipulate MenuItems from within onCreateOptionsMenu().
So this is how a sample Fragment class will look like.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
public static class MyFragment extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { menu.findItem(R.id.mymenuitem).setVisible(false); } } |
This code looks for the MenuItem and hides it.









