,可以通过以下步骤实现:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// 创建适配器并设置给RecyclerView
MyAdapter adapter = new MyAdapter(dataList);
recyclerView.setAdapter(adapter);
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Data> dataList;
public MyAdapter(List<Data> dataList) {
this.dataList = dataList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
// 绑定数据到ViewHolder中的CardView
Data data = dataList.get(position);
holder.cardView.setTitle(data.getTitle());
holder.cardView.setDescription(data.getDescription());
}
@Override
public int getItemCount() {
return dataList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.cardView);
}
}
}
在上述代码中,通过ViewHolder的构造函数获取了每个CardView的实例,并在onBindViewHolder
方法中将数据绑定到CardView中。
至此,你已经成功从Activity获取了RecyclerView中的CardView。这样可以方便地对CardView进行操作,例如修改其内容、添加点击事件等。
领取专属 10元无门槛券
手把手带您无忧上云