我正在尝试为我的一个片段中的ListView
设置适配器。但是,我收到一个空指针错误,我不知道什么是错的。
public class OptionsFragment extends Fragment{
ArrayAdapter<String> adapter;
//ArrayAdapter<String> adapter1 = ArrayAdapter.createFromResource
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.optionsfragmentnew, container, false);
ListView cListView = (ListView) rootView.findViewById(R.id.currencyListView);
String[] test = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, test);
//View v = inflater.inflate(R.layout.optionsfragmentnew, container, false);
cListView = (ListView) rootView.findViewById(android.R.id.list);
cListView.setAdapter(adapter);
return rootView;
}
}
答案 0 :(得分:0)
在onActivityCreated()
方法期间设置适配器,而不是在onCreateView()
期间设置适配器。
答案 1 :(得分:0)
我希望此代码可以帮助您
public class OptionsFragment extends Fragment {
ListView list;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_main, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
list = (ListView) getActivity().findViewById(R.id.list);
String[] test = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
ArrayAdapter adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, test);
list.setAdapter(adapter);
}
}