3

I need to listen when a fragment transaction is performed, for example, when I replace a fragment with another, without call to addToBackStack(). FragmentManager class provides a addOnBackStackChangedListener callback, but when I perform a fragment replacement without call to addToBackStack, it is not executed.

Edit: the listen operation is performed in a class which only have access to the activity instance and its fragment manager.

2 Answers2

1

You can use Base class for all your fragments. Then you can override onDetach() method. For example

public class BaseFragment extends Fragment {

@Override
public void onDetach() {
   // run code that needed by your library. e.g.
    if (getActivity() != null && getActivity() instanceof MainActivity) {
    ((MainActivity)getActivity()).someMethodToDetectOnDetach();
    }
    super.onDetach();
}

And then extends your fragments from BaseFragment like this

public class MyFragment extends BaseFragment {
// .....
}
Hank Moody
  • 354
  • 2
  • 15
0

You can use Fragment's onAttach() method.

Jan Slominski
  • 2,968
  • 4
  • 35
  • 61
  • The listen operation for fragment transactions is performed in a class which only have access to an activity instance and its FragmentManager. I will edit my question to clarify. – Victor Manuel Pineda Murcia Oct 11 '16 at 10:59
  • Did you ever figure this out? I have just tried an onBackStackChange listener but it never gets called even after setting it with the FragmentManager. – John Glen Oct 02 '20 at 02:42