3

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?

vm345
  • 813
  • 12
  • 28

3 Answers3

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

Possible duplicate?

@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);
Community
  • 1
  • 1
Kia
  • 124
  • 1
  • 1
  • 10