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)
}
相关推荐
IAM四十二9 天前
Google 端侧 AI 框架 LiteRT 初探
android·深度学习·tensorflow
CYRUS_STUDIO9 天前
手把手教你用 Chrome 断点调试 Frida 脚本,JS 调试不再是黑盒
android·app·逆向
Just丶Single9 天前
安卓NDK初识
android
编程乐学9 天前
网络资源模板--基于Android Studio 实现的咖啡点餐App
android·android studio·大作业·奶茶点餐·安卓移动开发·咖啡点餐
二流小码农9 天前
鸿蒙开发:基于node脚本实现组件化运行
android·ios·harmonyos
Wgllss9 天前
Kotlin+协程+FLow+Channel+Compose 实现一个直播多个弹幕效果
android·架构·android jetpack
顾林海10 天前
Android WebView内存释放全解析:从泄漏检测到彻底释放的实战指南
android·面试·性能优化
用户20187928316710 天前
🍕 披萨工厂奇遇记:Android APK打包之旅
android
程序猿陌名!10 天前
Android开发 原生设置-apps-里面隐藏应用信息
android
张风捷特烈10 天前
每日一题 Flutter#13 | build 回调的 BuildContext 是什么
android·flutter·面试