Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android fragment transaction listener

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.

like image 729
Victor Manuel Pineda Murcia Avatar asked Feb 27 '26 08:02

Victor Manuel Pineda Murcia


1 Answers

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 {
// .....
}
like image 55
Hank Moody Avatar answered Mar 01 '26 21:03

Hank Moody



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!