- 1,效果图
![image.png](https://i-blog.csdnimg.cn/blog_migrate/3b0e7da238ed0262008c6d9db6e4af9f.webp?x-image-process=image/format,png)
- 2,导包
implementation ‘com.android.support:recyclerview-v7:27.1.1’ - 3,Xml文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff">
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_one"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:overScrollMode="never"/>
</android.support.constraint.ConstraintLayout>
public class RvOneActivity extends AppCompatActivity {
private static final Integer []CATS = new Integer[]{
R.drawable.cat_1,
R.drawable.cat_2,
R.drawable.cat_3,
R.drawable.cat_4,
R.drawable.cat_5,
R.drawable.cat_6,
R.drawable.cat_7,
R.drawable.cat_8,
R.drawable.cat_9,
R.drawable.cat_10,
R.drawable.cat_11,
R.drawable.cat_12,
R.drawable.cat_13,
R.drawable.cat_14,
R.drawable.cat_15,
R.drawable.cat_16,
R.drawable.cat_17,
R.drawable.cat_18,
R.drawable.cat_19,
} ;
private RecyclerView rvone;
List<Integer> data;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rvone);
this.rvone = (RecyclerView) findViewById(R.id.rv_one);
StaggeredGridLayoutManager staggeredGridLayoutManager =
new StaggeredGridLayoutManager(4,
StaggeredGridLayoutManager.VERTICAL);
rvone.setLayoutManager(staggeredGridLayoutManager);
data = Arrays.asList(CATS);
rvone.setAdapter(new MyAdapter());
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(RvOneActivity.this).inflate(R.layout.item_rvone, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.ivIcon.setImageResource(data.get(position));
}
@Override
public int getItemCount() {
return data.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
ImageView ivIcon;
public ViewHolder(View itemView) {
super(itemView);
ivIcon = itemView.findViewById(R.id.iv_item_icon);
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/iv_item_icon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/cat_1"
android:scaleType="centerCrop"
android:layout_margin="1dp"
/>
</android.support.constraint.ConstraintLayout>