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);
        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

    }

}

我希望将 aListview与此 Fragment 一起使用,但我不知道该怎么做。在扩展 Activity 的普通类中可以使用new ArrayAdapter<String>(this, bla, bla),但我不能在扩展 Fragment 的类中这样做。我将如何做到这一点?

4

2 回答 2

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. 
于 2013-09-19T15:41:30.887 回答
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"};


}
于 2013-09-19T15:52:51.290 回答