2

I have an issue with onOptionsItemSelected event. My application consist of Activity, main fragment, multiple function fragments.

Activity's FragmentManager contains only one Fragment (MainFragment). MainFragment's ChildFragmentManager contains up to 5 fragments. All fragments are added by method:

public void addFragment(Fragment fragment) {
    FragmentManager fm = getChildFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.frame, fragment);
    ft.addToBackStack(fragment.getClass().getSimpleName());
    ft.commit();
}

All child fragments have their own menus. Every fragment has the same superclass with

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ...
    setHasOptionsMenu(true);
    ...
}

And it's own

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.clear();
    inflater.inflate(R.menu.some_menu, menu);
    ...
}

and

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    ...
}

All Menus are inflated properly, but onOptionsItemSelected(MenuItem item) is always called for the first fragment in backstack:

Let's say that I have:

  1. MainFragment (getChildFragmentManager)
  2. DetailsFragment
  3. EditFragment
  4. SelectionFragment

Menu is inflated from SelectionFragment, but when I press menu button, it calls DetailsFragment.onOptionsItemSelected...

MainActivity does not have Menu (none of mentioned methods).

How can I solve this issue?

Regards Jakub

Marian Przyszedł
  • 699
  • 1
  • 9
  • 19
  • Try to use `replace()` instead of `add()` when adding `fragment`s. Does the problem still persist? – NecipAllef May 30 '16 at 09:51
  • No, problem only occurs with add(). Unfortunately replace refreshes all views on popping backstack... – Marian Przyszedł May 30 '16 at 12:36
  • Your problem is that you are stacking fragments one on another by using `add()`. You should find a way to use either `replace()` or `hide()` to achieve what you are trying to achieve. `add()` isn't supposed to be used this way. – NecipAllef May 31 '16 at 00:58

0 Answers0