Android-使用RecyclerView的ItemDecoration 实现吸顶效果

最近看到这篇文章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)
        }
    }

以后再试试其他情况是否还有问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值