/**
* @author: hsw
* @date: 2021/8/23
* @desc:
*/
class GridDividerDecoration constructor(
@Px dividerSize: Float,
@ColorInt colorInt: Int,
private val spanCount: Int
) : RecyclerView.ItemDecoration() {
private val dividerPaint: Paint = Paint()
private val bounds = Rect()
init {
dividerPaint.color = colorInt
dividerPaint.strokeWidth = dividerSize
dividerPaint.style = Paint.Style.STROKE
dividerPaint.isAntiAlias = true
}
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
drawHorizontal(c, parent)
drawVertical(c, parent)
}
private fun drawHorizontal(canvas: Canvas, recyclerView: RecyclerView) {
val itemCount = recyclerView.adapter?.itemCount ?: 0
val childCount = recyclerView.childCount
val lastRowChildCount = getLastRowChildCount(itemCount)
for (i in 0 until childCount) {
val childView = recyclerView.getChildAt(i)
if (isChildInLastRow(recyclerView, childView, itemCount, lastRowChildCount)) {
continue
}
recyclerView.getDecoratedBoundsWithMargins(childView, bounds)
canvas.drawLine(
bounds.left.toFloat(),
bounds.bottom.toFloat(),
bounds.right.toFloat(),
bounds.bottom.toFloat(),
dividerPaint
)
}
}
private fun drawVertical(canvas: Canvas, recyclerView: RecyclerView) {
val childCount = recyclerView.childCount
val isRTL = ViewCompat.getLayoutDirection(recyclerView) == ViewCompat.LAYOUT_DIRECTION_RTL
for (i in 0 until childCount) {
val childView = recyclerView.getChildAt(i)
if (isChildInLastColumn(recyclerView, childView)) {
continue
}
recyclerView.getDecoratedBoundsWithMargins(childView, bounds)
val x = if (isRTL) bounds.left.toFloat() else bounds.right.toFloat()
canvas.drawLine(
x,
bounds.top.toFloat(),
x,
bounds.bottom.toFloat(),
dividerPaint
)
}
}
private fun getLastRowChildCount(itemCount: Int): Int {
val remainder = itemCount % spanCount
return if (remainder == 0) spanCount else remainder
}
private fun isChildInLastRow(
recyclerView: RecyclerView,
view: View,
itemCount: Int,
lastRowChildCount: Int
): Boolean {
return recyclerView.getChildAdapterPosition(view) >= itemCount - lastRowChildCount
}
private fun isChildInLastColumn(recyclerView: RecyclerView, view: View): Boolean {
return recyclerView.getChildAdapterPosition(view) % spanCount == spanCount - 1
}
}
这个是通过绘制的方式实现的边框。当然也可通过设置margin结合背景色的的方式进行实现