java - 如何将 Context 传递给 Fragment 类

标签 java android android-fragments android-context

我刚刚创建了一个 Fragment 类。此类绑定(bind)到包含 ListView 的布局。现在我想为此 ListView 设置一个适配器,但因此我需要一些“上下文”。 我可以通过构造函数将它们从 MainActivity 类转移到 Fragment 类,但 Eclipse 告诉我不要更改 Fragment 类的默认构造函数。然后我尝试设置一个

public static Context context;
MainActivity.context = this;

在 MainActivity 类中能够从任何地方访问此上下文,但再次出现一些错误。

如何在我的 Fragment 类中设置适配器? 它看起来像这样:

public static class LatestFragment extends Fragment {
    ListView listView;

    public LatestFragment() {

    }
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_latest, container, false);
        listView = (ListView) rootView.findViewById(R.id.fragment_latest_listview1);

        return rootView;
    }
}

正如你所看到的,我想为 listView 设置一个适配器。但我应该从哪里获取“上下文”?

最佳答案

您可以使用关联的 Activity 作为上下文,因为 Activity 是 Context 的间接子类。您可以像这样在 Fragment 中获取 Activity:

getActivity();

关于java - 如何将 Context 传递给 Fragment 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23459921/

相关文章:

java - 从 fragment 中的 Activity 调用方法

Java:操作以文本形式保存在 Clob/Blob 中的 docx 文档

android - 是否可以为连接到同一 wifi 的人创建聊天应用程序?

android - 仅在配备 Jelly Bean 的 Samsung S3 上,OpenGL 中的小屏幕尺寸

android - 在离线模式下开发Android应用程序

android - 两个 fragment 之间通过接口(interface)进行通信

java - 私有(private)不可变对象(immutable对象)的同步块(synchronized block)和同步方法的区别

java - 'new' 语句后的大括号有什么作用?

Android:屏幕方向更改 fragment.getActivity 为空

android - 滑动tabs的时候,fragment的oncreateView没有被调用,怎么每次都调用oncreateView