class SimpleDividerItemDecoration : RecyclerView.ItemDecoration() {
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
if (mSpanCount > 0) { //表示GridLayoutManager || StaggeredGridLayoutManager
drawHorizontal(c, parent)
drawVertical(c, parent)
} else { //表示LinearLayoutManager
if (isVertical) {
drawHorizontal(c, parent)
} else {
drawVertical(c, parent)
}
}
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
when (parent.layoutManager) {
is StaggeredGridLayoutManager -> {
(parent.layoutManager as StaggeredGridLayoutManager).apply {
mSpanCount = spanCount
outRect.set(0, 0, mDividerHeight, mDividerHeight)
}
}
is GridLayoutManager -> {
(parent.layoutManager as GridLayoutManager).apply {
mSpanCount = spanCount
outRect.set(0, 0, mDividerHeight, mDividerHeight)
}
}
is LinearLayoutManager -> {
if ((parent.layoutManager as LinearLayoutManager).orientation == LinearLayout.VERTICAL) {
outRect.set(0, 0, 0, mDividerHeight)
} else {
outRect.set(0, 0, mDividerHeight, 0)
isVertical = false
}
mSpanCount = 0
}
}
}
private fun drawVertical(c: Canvas, parent: RecyclerView) {
// -1表示忽略最后一个item
for (i in 0 until parent.childCount - 1) {
val child = parent.getChildAt(i)
var left = child.right
if (mSpanCount == 0) {
// 让分割线充满RecyclerView
left += parent.paddingRight
}
mDivider?.setBounds(left, child.top, left + mDividerHeight, child.bottom)
mDivider?.draw(c)
}
}
private fun drawHorizontal(c: Canvas, parent: RecyclerView) {
// -1表示忽略最后一个item
for (i in 0 until parent.childCount - 1) {
val child = parent.getChildAt(i)
val top = child.bottom
var left = child.left
var right = child.right
if (mSpanCount == 0) {
// 让分割线充满RecyclerView
left -= parent.paddingLeft
right += parent.paddingRight
}
mDivider?.setBounds(left, top, right, top + mDividerHeight)
mDivider?.draw(c)
}
}
}
网友评论