bean
public class Card {
private String name;
private String description;
public Card(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
子项xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/item_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp" />
<TextView
android:id="@+id/item_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp" />
</LinearLayout>
Adapter(内部重写ViewHolder)
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> {
private List<Card> cardList;
// adapter的构造方法
public CardAdapter(List<Card> cardList) {
this.cardList = cardList;
}
@NonNull
@Override
public CardViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view,parent,false);
return new CardViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CardViewHolder holder, int position) {
holder.name.setText(cardList.get(position).getName());
holder.description.setText(cardList.get(position).getDescription());
}
@Override
// 返回RecyclerView项目数量
public int getItemCount() {
return cardList.size();
}
// 存放RecyclerView的单个项,可以对这些项缓存复用,优化性能
static class CardViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView description;
// 此处重写的方法,传参是RecyclerView中的单个项的view
public CardViewHolder(@NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.item_name);
description = itemView.findViewById(R.id.item_description);
}
}
}
存放RecyclerView的xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>