RecyclerView系列之二(下) ItemDecoration

当我们在getItemOffsets设定的ourRect区域画一个矩形时,

java 复制代码
private val LEFT_OFFSETS = 300  //这里暂时先直接写死300px
kotlin 复制代码
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
    super.onDraw(c, parent, state)
    val mLayoutManager = parent.layoutManager
    for (index in 0 until parent.childCount) {
        val child = parent.getChildAt(index)
        //这里绘制一个矩形,左右边距20px方便观察
        c.drawRect(
            0f + 20f,
            child.height.toFloat() * (index),
            LEFT_OFFSETS.toFloat() - 20f,
            child.height.toFloat() * (index) + child.height.toFloat(),
            mPaint
        )
    }
}

当我们给改变边距时,

kotlin 复制代码
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
        val mLayoutManager = parent.layoutManager
        for (index in 0 until parent.childCount) {
            val child = parent.getChildAt(index)
            //这里绘制一个矩形,左右边距20px方便观察
//            c.drawRect(
//                0f + 20f,
//                child.height.toFloat() * (index),
//                LEFT_OFFSETS.toFloat() - 20f,
//                child.height.toFloat() * (index) + child.height.toFloat(),
//                mPaint
//            )
            //这里绘制一个矩形,右边距超过所给outRect的20px看效果
            c.drawRect(0f, child.height.toFloat()*(index),
                LEFT_OFFSETS.toFloat()+20f, child.height.toFloat()*(index)+child.height.toFloat(), mPaint)
        }
    }

可以看到所绘制的矩形超出getItemOffsets方法设定的outRect范围的部分将是不可见的,这是因为在整个绘制流程中,先调用ItemDecoration的onDraw方法,再调用Item的onDraw方法,最后调用ItemDecoration的onDrawOver方法。 所以在ItemDecoration的onDraw函数中绘制的内容时,当超出边界,会被Item所覆盖,但是因为最后才调用onDrawOver方法,所以它绘制的内容不受outRect边界的限制,可以覆盖Item的区域显示。

绘制渐变蒙版,因为蒙版是浮在Item之上的,可以在onDrawOver中绘制。

kotlin 复制代码
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
    super.onDrawOver(c, parent, state)
    //画蒙版
    val temp = parent.getChildAt(0)
    val gradient = LinearGradient(
        parent.width / 2f, 0f, parent.width / 2f, temp.height * 4f,
        -0xffff01, 0x000000ff, Shader.TileMode.CLAMP
    )
    mPaint.shader = gradient
    c.drawRect(0f, 0f, parent.width.toFloat(), (temp.height * 4).toFloat(), mPaint)
}
相关推荐
用户20187928316710 小时前
Android黑夜白天模式切换原理分析
android
芦半山10 小时前
「幽灵调用」背后的真相:一个隐藏多年的Android原生Bug
android
卡尔特斯10 小时前
Android Kotlin 项目代理配置【详细步骤(可选)】
android·java·kotlin
ace望世界10 小时前
安卓的ViewModel
android
ace望世界10 小时前
kotlin的委托
android
CYRUS_STUDIO13 小时前
一文搞懂 Frida Stalker:对抗 OLLVM 的算法还原利器
android·逆向·llvm
zcychong13 小时前
ArrayMap、SparseArray和HashMap有什么区别?该如何选择?
android·面试
CYRUS_STUDIO13 小时前
Frida Stalker Trace 实战:指令级跟踪与寄存器变化监控全解析
android·逆向
ace望世界18 小时前
android的Parcelable
android
顾林海18 小时前
Android编译插桩之AspectJ:让代码像特工一样悄悄干活
android·面试·性能优化