gpt4 book ai didi

android - ListView 不使用 ArrayAdapter 在 fragment 中显示数据

转载 作者:搜寻专家 更新时间:2023-11-01 09:36:13 33 4
gpt4 key购买 nike

我创建了一个 fragment ,我想在其中显示 ListView ,但我的 fragment 在没有 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;}}}

最佳答案

你没有给字符串数组赋值:使用

servicesNameArray = getResources().getStringArray(R.array.servicesName);  

而不是:

 ServicesAdapter adapter = new ServicesAdapter(getContext(), servicesNameArray, serviceImages);

使用 Activity 上下文:

ServicesAdapter adapter = new ServicesAdapter(this.getActivity(), servicesNameArray, serviceImages);

您需要通知适配器您的数据集大小:

super(context, R.layout.services_layout, servicesNameArray); //change here

关于android - ListView 不使用 ArrayAdapter 在 fragment 中显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43029091/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com