最近看到这篇文章https://blog.csdn.net/cjm2484836553/article/details/53453982, 然后自己就研究研究,发现有一些问题,然后自己也根据这篇文章改了一些逻辑
主要是在原来的代码中,如果item的高度小于定义的decoration的高度时,源代码是根据前后两个item位置的再进行高度变化,这样会导致高度变化不准确
我对这块儿的代码进行一定的优化,根据每个组的第一个item的距顶部距离小于两个decoration的高度时,进行高度变化,这样就不会有高度变化延迟了,看代码吧
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDrawOver(c, parent, state)
val left = parent.paddingLeft.toFloat()
val right = (parent.width - parent.paddingRight).toFloat()
val manager = parent.layoutManager as LinearLayoutManager
var childCount = parent.childCount
var itemCoubnt = state.itemCount
var nextPosition = 0
for (i in 0 until childCount){
var view = parent.getChildAt(i)
var position = parent.getChildAdapterPosition(view)
Log.e("why", "position=$position")
if(position % 10 != 0 && position != manager.findFirstVisibleItemPosition()) continue
if(nextPosition == 0){
nextPosition = position - position % 10 + 10
}
var viewBottom = view.bottom
var textY = kotlin.math.max(mHeight, view.top)
var nextView = parent.findViewHolderForLayoutPosition(nextPosition)!!.itemView
// Log.e("position","position=$position")
if(position + 1 < itemCoubnt){
// Log.e("textYChange", "nextView.top=${nextView.top}, nextIndex=$nextPosition")
if((nextPosition != 0 && nextView.top < mHeight * 2) && position % 10 != 0){
// || (position % 10 == 9) && viewBottom < textY
textY = nextView.top - mHeight
}
}
// Log.e("textY", "textY=$textY")
c.drawRect(0f, (textY - mHeight).toFloat(), right, textY.toFloat(), mPaint)
// Log.e("top", "top=$top, bottom=$bottom")
val tag = tagListener(position)
textPaint.getTextBounds(tag, 0, tag.length, mRound)
c.drawText(tag, left + textPaint.textSize, textY.toFloat() - mHeight / 2 + mRound.height() / 2, textPaint)
}
}
以后再试试其他情况是否还有问题