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)
}
相关推荐
jiet_h31 分钟前
Android锁
android
teacher伟大光荣且正确9 小时前
Qt Creator 配置 Android 编译环境
android·开发语言·qt
飞猿_SIR11 小时前
Android Exoplayer 实现多个音视频文件混合播放以及音轨切换
android·音视频
HumoChen9912 小时前
GZip+Base64压缩字符串在ios上解压报错问题解决(安卓、PC模拟器正常)
android·小程序·uniapp·base64·gzip
沙振宇16 小时前
【HarmonyOS】ArkTS开发应用的横竖屏切换
android·华为·harmonyos
橙子1991101617 小时前
Kotlin 中的作用域函数
android·开发语言·kotlin
zimoyin17 小时前
Kotlin 懒初始化值
android·开发语言·kotlin
枣伊吕波18 小时前
第六节第二部分:抽象类的应用-模板方法设计模式
android·java·设计模式
萧然CS18 小时前
使用ADB命令操作Android的apk/aab包
android·adb
_extraordinary_1 天前
MySQL 事务(二)
android·数据库·mysql