我最近一直在处理 fragment ,我只是想知道使用对 fragment 父 Activity 的引用的最佳做法是什么。继续调用 getActivity() 还是在 onActivityCreated 回调中初始化 parentActivity 变量会更好。
最佳答案
这其实包含在Android官方文档中关于Fragments的部分。当您需要父 Activity 的上下文(例如 Toast、Dialog)时,您可以调用 getActivity()
。当您需要调用 Fragment 接口(interface)中的回调方法时,您应该使用在 onAttach(...)
中实例化的回调变量。
public static class FragmentA extends ListFragment {
ExampleFragmentCallbackInterface mListener;
...
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (ExampleFragmentCallbackInterface ) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement ExampleFragmentCallbackInterface ");
}
}
...
}
关于android - 引用 fragment 父 Activity 的最佳做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13116104/