前言
recycleView 的item等分开发中经常用到,实现方案多样。
比如:
1.计算屏幕宽度除以等分数,然后动态设置item的宽高进行等分。
2.固定item数量,通过调整padding 内边距或者调整margin 外边距达到等分。
3.通过简单设置recycleView属性,让系统自动进行适配达到等分。
这里介绍下只用布局属性方式进行等分。
最终设置如下:
#源码
val gridLayoutManager =
GridLayoutManager(this@PlayTogetherActivity, 5)
gridLayoutManager.orientation = RecyclerView.VERTICAL
recycleView.layoutManager = gridLayoutManager
#布局
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/refreshViewChild"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/img_arrow"
android:layout_gravity="center_horizontal" />
# item布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:paddingLeft="9dp"
android:paddingBottom="12dp"
android:paddingRight="9dp"
android:id="@+id/ll_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
...
... 省略...
...
</LinearLayout>
下图为按照上面配置后的效果。
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiQDOxEzX3xCZlhXam9VbsUmepNXZy9CXwJWZ3xCdh1mcvZ2Lc1zaHRGcWdUYuVzVa9GczoVdG1mWfVGc5RHLwIzX39GZhh2csATMflHLwEzX4xSZz91ZsAzMfRHLGZkRGZkRfJ3bs92YskmNhVTYykVNQJVMRhXVEF1X0hXZ0xiNx8VZ6l2cssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLzITN1EmZyUWN4QTN4QjNzYzX0QTMyETM0AzLcFTMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
eg: 这里贴出来不符合设置属性的效果
1.不设置居中效果
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/refreshViewChild"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/img_arrow"
/>