Android fragment transaction listener

泪湿孤枕 提交于 2020-01-04 09:28:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!