问题
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.
回答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 {
// .....
}
回答2:
You can use Fragment's onAttach() method.
来源:https://stackoverflow.com/questions/39975529/android-fragment-transaction-listener