ListView在片段中变为null

时间:2016-12-09 10:37:43

标签: android listview android-fragments

我正在尝试使用相应的Adapter定义listview,以将字符串添加到listview。 Howevewr,我的listview是null。代码如下: -

public class CategoryFragment extends Fragment {
....
....
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {


    ListView listView = (ListView) getActivity().findViewById(R.id.cat_vacancies);
    listAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_2);
    listView.setAdapter(listAdapter);

....

}
}

此时我做错了什么?

我的片段xml如下(我只添加了我认为可能有助于诊断问题的相关部分)

<RelativeLayout>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/cat_vacancies">

    </ListView>

</RelativeLayout>

P.S。据我所知,这是一个愚蠢的错误,但我还没有完全掌握android,所以请原谅我的问题。

2 个答案:

答案 0 :(得分:1)

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

View view=inflater.inflate(R.layout.[layout id], container, false);
    ListView listView = (ListView) view.findViewById(R.id.cat_vacancies);
retrun view;
}

答案 1 :(得分:1)

以那种方式尝试

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

    ListView listView = (ListView) view.findViewById(R.id.cat_vacancies);
    listAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_2);
    listView.setAdapter(listAdapter);

....

}