此代码来自recyclerd教程,即我试图使用getdata
函数将数据绑定到recyclerview
public static List<Information> getData()
{
List<Information> menuData=new ArrayList<>();
int[] icons={R.drawable.ic_bluetooth,R.drawable.ic_crosshairs_gps,R.drawable.ic_laptop,R.drawable.ic_remote};
String[] titles={"Bluetooth","GPS","Laptop","Remote"};
for(int i=0;i<titles.length&&i<icons.length;i++)
{
Information current =new Information();
current.iconID=icons[i];
current.title=titles[i];
menuData.add(current);
}
return menuData;
}
for循环中的最后一次迭代显示menuData
列表中的4个项目
但iAdapter
显示数据大小= 0
InformationAdapter
public class InformationAdapter extends RecyclerView.Adapter<InformationAdapter.infoViewholder> {
private LayoutInflater inflator;
List<Information> data=Collections.emptyList();
public InformationAdapter(Context context, List<Information> data) {
inflator= LayoutInflater.from(context);
}
@Override
public infoViewholder onCreateViewHolder(ViewGroup parent, int i) {
View view= inflator.inflate(R.layout.custom_row,parent,false);
infoViewholder holder=new infoViewholder(view);
return holder;
}
@Override
public void onBindViewHolder(infoViewholder holder, int position) {
Information current=data.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconID);
}
@Override
public int getItemCount()
{
return data.size();
}
class infoViewholder extends RecyclerView.ViewHolder
{
TextView title;
ImageView icon;
public infoViewholder(View itemView) {
super(itemView);
title= (TextView) itemView.findViewById(R.id.list_text);
icon= (ImageView) itemView.findViewById(R.id.text_icon);
}
}
}
答案 0 :(得分:2)
问题是您没有引用刚刚在构造函数中传递的数据列表,因此数据列表为空:
public InformationAdapter(Context context, List<Information> data) {
inflator= LayoutInflater.from(context);
}
应该是
public InformationAdapter(Context context, List<Information> data) {
inflator= LayoutInflater.from(context);
this.data = data;
}