使用
RecyclerView.ItemDecoration用来装饰RecyclerView的itemView,我们常用来做分割线,但它的功能不仅是分割线。
实现ItemDecoration,需要实现子类,主要实现他的两个主要方法
/**
这个方法主要是获取itemView的范围
outRect就是扩展参数,0表示范围跟itemView范围一样。
>0表示范围外扩(如果无法外扩则边界预留)。
outRect.top=10,表示上边界外扩 10px (可以理解为marginTop = 10,这些区域用于绘制边界,不会用于itemView的展示)
**/
override fun getItemOffsets(
outRect: Rect, view: View, parent: RecyclerView,state: RecyclerView.State
)
/**
画装饰条目,需要绘制出全部item的装饰。一般根据itemView的LayoutParam,定位到canvas绘制的位置
**/
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State)
代码片
package com.me.kotlinlearn
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
class MyDecoration(val isVertical: Boolean, val colorValue:Int, val size:Int) : RecyclerView.ItemDecoration() {
public constructor() : this(false, Color.parseColor("#ff000000"), 100)
private val paint = Paint().apply {
flags = Paint.ANTI_ALIAS_FLAG
color = colorValue
}
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
super.getItemOffsets(outRect, view, parent, state)
if(isVertical) {
outRect.set(0, 0, size, 0)
} else {
outRect.set(0, 0, 0, size)
}
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDraw(c, parent, state)
if (isVertical) {
drawVertical(c, parent, state)
} else {
drawHorizontal(c, parent, state)
}
}
/**
* 画水平分割线
*/
private fun drawHorizontal(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
for(i in 0 until parent.childCount) {
val child = parent.getChildAt(i)
val param = child.layoutParams as RecyclerView.LayoutParams
val left = child.left - param.leftMargin
val top = child.bottom + param.bottomMargin
val right = child.right + param.rightMargin
val bottom = top + size
c.drawRect(Rect(left, top, right, bottom), paint)
}
}
/**
* 画竖直分割线
**/
private fun drawVertical(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
for(i in 0 until parent.childCount) {
val child = parent.getChildAt(i)
val param = child.layoutParams as RecyclerView.LayoutParams
val left = child.right + param.rightMargin
val top = child.top - param.topMargin
val right = left + size
val bottom = child.bottom + param.bottomMargin
c.drawRect(Rect(left, top, right,bottom), paint)
}
}
}
RecyclerView提供的ItemDecoration
DividerItemDecoration
用来为线性布局提供分割线。分割线可直接在layout中实现。