前言
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"
/>