无法获取片段中的列表(Android Studio)

时间:2017-06-05 14:23:02

标签: android android-studio android-fragments

为什么我无法在片段中获取listview。我已经创建了列表以及项目。我添加了项目,但无法理解这一点。请帮我理解一下。我复制了它并进行了编辑。

这是我的代码:

public class NewsFragment extends Fragment {
private ListView mListView;
private List<String> mNewsList;

public NewsFragment() {
    // Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View frag = inflater.inflate(R.layout.fragment_news, container,                                                                                                                             false);
    mListView = (ListView) frag.findViewById(R.id.MyListView);

    mNewsList = new ArrayList<String>();
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");
    mNewsList.add("gjjggj");

 //   mListView.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,android.R.id.text1,mNewsList));
    mListView.setAdapter(new MyAdapter());
    return frag;

}
private class MyAdapter extends BaseAdapter{

    @Override
    public int getCount() {
        return mNewsList.size();
    }

    @Override
    public Object getItem(int position) {
        return mNewsList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowview = getActivity().getLayoutInflater().inflate(R.layout.row,null);
        return rowview;
    }
  }
}

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您只是将适配器添加到listview,但没有数据资源是否有适配器..

mListView.setAdapter(new MyAdapters());

尝试将arrayAdapter用于数据源,如String数组

mListView.setAdapter(new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_1, android.R.id.text1, mNewsList));

和mNewsList应为String []。