recyclerview实现两列网格图片展示
时间: 2023-12-14 18:38:41 浏览: 144
RecyclerView仿应用列表实现网格布局
要实现RecyclerView的两列网格图片展示,可以使用GridLayoutManager布局管理器。
首先,在XML文件中添加RecyclerView:
```
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
然后,在Java代码中设置RecyclerView的布局管理器和适配器:
```
// 设置布局管理器,每行显示两个item
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
// 设置适配器
MyAdapter adapter = new MyAdapter(dataList);
recyclerView.setAdapter(adapter);
```
其中,MyAdapter是自定义的适配器,需要重写RecyclerView.Adapter的三个方法:onCreateViewHolder、onBindViewHolder和getItemCount。在ViewHolder中添加ImageView并设置图片即可:
```
class MyViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public MyViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image_view);
}
}
class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private List<Integer> dataList;
public MyAdapter(List<Integer> dataList) {
this.dataList = dataList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.imageView.setImageResource(dataList.get(position));
}
@Override
public int getItemCount() {
return dataList.size();
}
}
```
其中,item_image.xml是每个item的布局文件,可以根据需求自定义。
阅读全文