在oncreateview方法的片段中使用listview.setadapter()的空指针异常

时间:2016-03-09 20:40:20

标签: android

public View onCreateView(LayoutInflater inflater,ViewGroup容器,                              Bundle savedInstanceState){         查看v = inflater.inflate(R.layout.fragment_main,container,false);

    String[] data = {
            "Mon 6/23 - Sunny - 31/17",
            "Tue 6/24 - Foggy - 21/8",
            "Wed 6/25 - Cloudy - 22/17",
            "Thurs 6/26 - Rainy - 18/11",
            "Fri 6/27 - Foggy - 21/10",
            "Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18",
            "Sun 6/29 - Sunny - 20/7"
    };
    ArrayList<String> listforecast = new ArrayList<String>(Arrays.asList(data));


    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forcast_,
            R.id.listitem_forcast_textview, listforecast);

    listView = (ListView) container.findViewById(R.id.listview_display);
    listView.setAdapter(adapter);

    return v;
} 

fragment.xml之

<!-- TODO: Update blank fragment layout -->
<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/listview_display"
    ></ListView>

1 个答案:

答案 0 :(得分:4)

替换:

listView = (ListView) container.findViewById(R.id.listview_display);

listView = (ListView) v.findViewById(R.id.listview_display);