Android - How to hide menu option for current fragment
First get the item you want to remove :
MenuItem item = menu.findItem(R.id.your_action);
then set it's Visibility false
:
item.setVisible(false);
and if the problem is in getting the menu (as it's not in the fragment), you can easily get a context
from the activity that contains the menu and get the menu by it.
Inside your fragment you will have to use setHasOptionsMenu(true); in order to access options menu from within your fragment.
Code (inside your second fragment where you wanna hide the item):
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO your code to hide item here
super.onCreateOptionsMenu(menu, inflater);
}
Similarly, for your fragment where you want to show that MenuItem you can do the similar thing.
In the fragment where you want to hide the Item
@Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item=menu.findItem(R.id.action_search);
item.setVisible(false);
and in onCreate()
of your fragment
setHasOptionsMenu(true);