如何在扩展片段的类中创建ArrayAdapter?

时间:2013-09-19 15:40:25

标签: android listview

我的代码:

public class NewsFeedActivity extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.activity_news_feed, container, false);
        return view;

    }
    ListView l;
    String[] names={"Schuyler", "Faraz"};
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        l= (ListView) getView().findViewById(R.id.listView1);
        ArrayAdapter<String> ad=new ArrayAdapter<String>(this, android.R.layout.simple_gallery_item, names);//Here is the problem

    }

}

我希望在此片段中使用Listview,但我不知道该怎么做。在扩展Activity的普通类中,将使用new ArrayAdapter<String>(this, bla, bla),但我不能在扩展Fragment的类中执行此操作。我该如何做到这一点?

2 个答案:

答案 0 :(得分:1)

使用getActivity代替this

ArrayAdapter<String> ad=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_gallery_item, names);

public final Activity getActivity ()

Added in API level 11
Return the Activity this fragment is currently associated with. 

答案 1 :(得分:0)

请尝试以下代码:

public class NewsFeedActivity extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.activity_news_feed, container, false);
        l= (ListView) view.findViewById(R.id.listView1);
        ArrayAdapter<String> ad=new ArrayAdapter<String>(getActivity(), android.R.layout.simple_gallery_item, names);
        l.setAdapter(ad);
        return view;
    }
    private ListView l;
    private String[] names={"Schuyler", "Faraz"};


}