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)
}
相关推荐
每次的天空1 小时前
Android第十五次面试总结(第三方组件和adb命令)
android
追随远方1 小时前
Android音频开发:Speex固定帧与变长帧编解码深度解析
android·音视频
消失的旧时光-19431 小时前
Android和硬件通信
android
0wioiw01 小时前
安卓基础(编译.Class)
android
0wioiw01 小时前
安卓基础(aar)
android
_一条咸鱼_1 小时前
Android Runtime链接(Linking)阶段准备工作(27)
android·面试·android jetpack
aqi003 小时前
FFmpeg开发笔记(六十四)使用国产的RedPlayer播放器观看网络视频
android·ffmpeg·音视频·直播·流媒体
雨白3 小时前
扩展函数和运算符重载
android
casual_clover4 小时前
Android Studio 解决首次安装时下载 Gradle 慢问题
android·ide·android studio
天天爱吃肉82184 小时前
新能源汽车热管理核心技术解析:冬季续航提升40%的行业方案
android·python·嵌入式硬件·汽车