天天看點

RecycleVeiw 多列等分實作

前言

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>      

下圖為按照上面配置後的效果。

RecycleVeiw 多列等分實作

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