How to get the Activity in nested fragments?

两盒软妹~` 提交于 2019-12-02 03:27:55

Every fragment, even those that are childen of another fragment, receive a call to onAttach() when they are added to the fragment tree. The activity containing the fragment is passed in as a parameter. The simplest solution is may be to save the activity as a member of your fragment. Then it is available when needed later.

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    //save the activity to a member of this fragment
    mHostActivity = activity;
}

An alternative, for a fragment that is always at a fixed depth in the tree, is to use getParent() as many times as needed to get to the top-most fragment. For example, in your fragments that are children of the pager fragment:

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