val left = 0f val right = parent.width.toFloat() val childCount = parent.childCount for (i in0 until childCount) { val child = parent.getChildAt(i) val pos = parent.getChildAdapterPosition(child) if (pos == RecyclerView.NO_POSITION || !isFirstInGroup(pos)) continue
val top = child.top - mHeight.toFloat() val bottom = top + mHeight.toFloat() c.drawRect(left, top, right, bottom, mPaint)
val title = callback.getGroupTitle(pos) c.drawText(title, left, top + mHeight / 2 + mTextPaint.baselineShift, mTextPaint) } }
// 判断item是否所在组的内第一个item privatefunisFirstInGroup(pos: Int): Boolean { if (pos < 0) returnfalse val index = callback.getGroupIndex(pos) val preIndex = callback.getGroupIndex(pos - 1) return index != preIndex }
// 绘制StickyHeader overridefunonDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { super.onDrawOver(c, parent, state) val manager = parent.layoutManager as LinearLayoutManager // 找到RecyclerView第一个可见的itemView在adapter中的位置 val firstPos = manager.findFirstVisibleItemPosition() if (firstPos == RecyclerView.NO_POSITION) return
if (isLastInGroup(firstPos)) { // 标题要跟着组内最后一个滑走 val child = parent.findViewHolderForAdapterPosition(firstPos)?.itemView ?: return val bottom = min(child.bottom, mHeight).toFloat() val top = bottom - mHeight.toFloat() val left = 0f val right = parent.width.toFloat() c.drawRect(left, top, right, bottom, mPaint)
val title = callback.getGroupTitle(firstPos) c.drawText(title, left, top + mHeight / 2 + mTextPaint.baselineShift, mTextPaint) } else { // 直接绘制在顶部 val top = 0f val bottom = mHeight.toFloat() val left = 0f val right = parent.width.toFloat() c.drawRect(left, top, right, bottom, mPaint)
val title = callback.getGroupTitle(firstPos) c.drawText(title, left, top + mHeight / 2 + mTextPaint.baselineShift, mTextPaint) } }
// 判断item是否所在组的内最后一个item privatefunisLastInGroup(pos: Int): Boolean { if (pos < 0) returnfalse val index = callback.getGroupIndex(pos) val preIndex = callback.getGroupIndex(pos + 1) return index != preIndex }