如何将Context转移到Fragment类

时间:2014-05-04 18:23:30

标签: java android android-fragments android-context

我刚刚创建了一个Fragment类。此类绑定到包含ListView的布局。现在我想为这个ListView设置一个适配器,但是因此我需要一些" context"。 我可以通过构造函数将它们从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。但是我应该在哪里获得" context"从?

1 个答案:

答案 0 :(得分:2)

您可以使用关联的Activity作为上下文,因为Activity是Context的间接子类。你可以在片段中得到这样的活动:

getActivity();