android - 引用 fragment 父 Activity 的最佳做法?

标签 android

我最近一直在处理 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 ");
        }
    }
    ...
}

Source

关于android - 引用 fragment 父 Activity 的最佳做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13116104/

相关文章:

java - 我的代码在 Android 中使用多线程吗?

java - 停止 fragment 的函数和调用并重置内部变量

android - 在没有 RadioGroup 的情况下使用 RadioButtons?

Android - 将文件保存到内部存储器

android - 在 android 中使用 cordova 重定向到位置设置

android - 从 Android 应用程序托管本地网页

Android Studio 没有使用 gradle 来构建我的项目

android - 从代码中启用或禁用 PatternLock 屏幕

java - 如何在android项目中包含selenium库?

android - 使用倾斜传感器的 Arduino 程序中的正确功能顺序