package com.geely.galaxy.car.ui.adapter.decoration
import android.graphics.Rect
import androidx.recyclerview.widget.RecyclerView
import com.geely.market.energy.common.util.ScreenUtils
import kotlin.properties.Delegates
class GridDecoration : RecyclerView.ItemDecoration {
private var spaceCount :Int
private var itemWidth :Int
private var columnSpacing = 0
private val rvWidth by lazy {
ScreenUtils.getScreenWidth()
}
constructor(count: Int, itemWidth: Int) {
this.spaceCount = count
this.itemWidth = itemWidth
columnSpacing = (rvWidth - (itemWidth * spaceCount)) / (spaceCount -1)
}
fun updateSpaceCount(count :Int){
this.spaceCount = count
columnSpacing = (rvWidth - (itemWidth * spaceCount)) / (spaceCount -1)
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildAdapterPosition(view) // 获取view 在adapter中的位置。
val column = position % spaceCount // view 所在的列
outRect.left = (column * columnSpacing / spaceCount).toInt() // column * (列间距 * (1f / 列数))
outRect.right = (columnSpacing - (column + 1) * columnSpacing / spaceCount).toInt() // 列间距 - (column + 1) * (列间距 * (1f /列数))
}
}
RecyclerView两端对齐ItemDecoration
于 2023-05-23 16:31:29 首次发布