I need to avoid showing of menu items of one fragment in the other one. That is in fragment A i need menu items . And in fragment B i don't need it. But When i try to make transition from fragment A to fragment B. The menu item of fragment A is showing in fragment B. How do I solve the conflicts?
Asked
Active
Viewed 2,065 times
3
-
1this is likely caused by misuse of `onCreateOptionsMenu` in your fragments – Vladyslav Matviienko Apr 12 '17 at 05:58
-
check this [link](http://stackoverflow.com/a/21498812/5882539) for your solution – Ashish M Apr 12 '17 at 06:00
3 Answers
9
I also faced this problem and i solved it by doing this
In onCreate method do this
@Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
In onCreateOptionMenu do this
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
}

Kshitij Arora
- 287
- 3
- 9
2
In the Fragment where you don't want to show any menu options, you need setHasOptionsMenu(false);
in the onCreate(),
like this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
However, the menu that is being shown that you would like to hide , belongs to MainActivity. That is why it is always shown. Since you want to control the menu at the Fragment level, my suggestion is to delete the menu code from the Activity and implement it in your Fragment. Activity and fragments can have their own seperate menus as described in the android developer site - https://developer.android.com/guide/topics/ui/menus.html#options-menu

Fathima km
- 2,539
- 3
- 18
- 26
0
@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);