我有一个创建了一个片段,我想在其中显示listview,但我的片段在列表视图中不显示,但我收到错误
我已经阅读了很多这个问题的解决方案,但我找不到合适的解决方案。 一个小小的帮助会很棒。谢谢你!
public class ServicesFragment extends Fragment {
public TextView servicesName;
ListView listView;
String[] servicesNameArray;
int[] serviceImages = {
R.drawable.ic_menu_camera,
R.drawable.ic_menu_camera,
R.drawable.ic_menu_camera,
R.drawable.ic_menu_camera,
R.drawable.ic_menu_camera,
R.drawable.ic_menu_camera,
R.drawable.ic_menu_camera,
R.drawable.ic_menu_camera
};
public ServicesFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.services_fragment, container, false);
listView = (ListView) view.findViewById(R.id.listView_services);
ServicesAdapter adapter = new ServicesAdapter(getContext(), servicesNameArray, serviceImages);
listView.setAdapter(adapter);
Resources resources = getResources();
resources.getStringArray(R.array.servicesName);
return view;
}
public class ServicesAdapter extends ArrayAdapter<String> {
Context c;
int[] servicesImageArray;
String[] servicesNameArray;
public ServicesAdapter(Context context, String[] servicesNameArray, int[] serviceImages) {
super(context, R.layout.services_layout, R.id.listView_services);
this.c = context;
this.servicesImageArray = serviceImages;
this.servicesNameArray = servicesNameArray;
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.services_layout, parent, false);
ImageView serviceImages = (ImageView) view.findViewById(R.id.image_of_services);
TextView servicesName = (TextView) view.findViewById(R.id.name_of_services);
serviceImages.setImageResource(servicesImageArray[position]);
servicesName.setText(servicesNameArray[position]);
return view;}}}
答案 0 :(得分:2)
您没有为字符串数组赋值:使用
servicesNameArray = getResources().getStringArray(R.array.servicesName);
而不是:
ServicesAdapter adapter = new ServicesAdapter(getContext(), servicesNameArray, serviceImages);
使用活动上下文:
ServicesAdapter adapter = new ServicesAdapter(this.getActivity(), servicesNameArray, serviceImages);
您需要通知适配器您的数据集大小:
super(context, R.layout.services_layout, servicesNameArray); //change here
答案 1 :(得分:0)
我认为这个问题导致你没有以正确的方式传递数据
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.services_fragment, container, false);
Resources resources = getResources();
servicesNameArray = resources.getStringArray(R.array.servicesName);
listView = (ListView) view.findViewById(R.id.listView_services);
ServicesAdapter adapter = new ServicesAdapter(getContext(), servicesNameArray, serviceImages);
listView.setAdapter(adapter);
return view;
}