片段中列表视图的问题

时间:2017-12-06 20:00:36

标签: android listview android-fragments

我正在尝试在片段中创建包含图像和文本的列表视图,但我无法让它工作。我得到某种错误,告诉我我尝试在null上调用set Adapter方法对象。我做错了什么

public class SecondFragment extends Fragment {
String[] listviewTitle = new String[]{"Drew Parker","Maggie Smith","Michael John","Luisa Miller","Loredana Marie","Cristopher Smidth","Michelle Acapella","John Fitzgerald"

};
int[] listviewImage = new int[]{
        R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile, R.drawable.profile,

};
String[] listviewShortDescription = new String[]{
        "Android ListView Short Description", "Android ListView Short Description", "Android ListView Short Description", "Android ListView Short Description",
        "Android ListView Short Description", "Android ListView Short Description", "Android ListView Short Description", "Android ListView Short Description",
};

public SecondFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    List<HashMap<String, String>> aList = new ArrayList<>();
    for (int i = 0; i < 8; i++) {
        HashMap<String, String> hm = new HashMap<>();
        hm.put("listview_title", listviewTitle[i]);
        hm.put("listview_discription", listviewShortDescription[i]);
        hm.put("listview_image", Integer.toString(listviewImage[i]));
        aList.add(hm);
    }
    String[] from = {"listview_image", "listview_title", "listview_discription"};
    int[] to = {R.id.listview_image, R.id.listview_item_title, R.id.listview_item_short_description};

    SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.tab2fragment, from, to);
    ListView listView=(ListView)getActivity().findViewById(R.id.list_view);
    listView.setAdapter(simpleAdapter);
}

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

    return view;
}

}

1 个答案:

答案 0 :(得分:1)

从onCreate中删除小部件初始化,并将其放在onCreateView中,如下所示。

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {


    View view=inflater.inflate(R.layout.listview_withimages_andnames,container,false);

    SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.tab2fragment, from, to);

    ListView listView=(ListView) view.findViewById(R.id.list_view);
    listView.setAdapter(simpleAdapter);


return view;   }

并替换

getActivity().findViewById(R.id.list_view)

通过

view.findViewById(R.id.list_view)

因为您应该从onCreateView中初始化的片段布局中获取您的Recycler视图,而不是来自活动