代码
- 首先在gradle中添加依赖
dependencies {
...
implementation 'androidx.recyclerview:recyclerview:1.0.0'
}
- 定义一个适配器
需要继承自RecyclerView.Adapter<FruitAdapter.ViewHolder>,传入泛型类型。
public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
private List<Fruit> fruitList;
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView fruitImage;
TextView fruitName;
View fruitView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
fruitView = itemView;
fruitImage = itemView.findViewById(R.id.fruit_image);
fruitName = itemView.findViewById(R.id.fruit_name);
}
}
public FruitAdapter(List<Fruit> fruitList) {
this.fruitList = fruitList;
}
@NonNull
@Overri