首页 > 解决方案 > 如何将自定义 XML 布局膨胀到自定义 ItemDecoration?

问题描述

我希望在我的 RecyclerView 中添加一个自定义 ItemDecoration,它是在 XML 文件中定义的布局。

到目前为止,我能够使用 canvas.translate 扩展 XML 和位置(但是,没有理解所有内容)。

目前我有这个代码来绘制:

override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {

        for (i in 0 until parent.childCount) {
            val child = parent.getChildAt(i)

            val left = child.marginLeft
            val top = child.top

            context?.let {

                //Inflate the Layout and set the Values (a text in this case)
                val view = LayoutInflater.from(it).inflate(R.layout.my_decoration_layout, parent, false)
                val textView = view.findViewById<TextView>(R.id.textView)
                textView.text = "This is an ItemDecoration"

                //Calculate the Size. Im using "hardcoded" values, but this does not seems to change how the View is rendered
                view.measure(1000,1000)
                view.layout(0, 0, 1000, 1000)

                //Draw. I had to translate the canvas to apply the offset for each "ViewHolder"
                canvas.save()
                canvas.translate(left.toFloat(), top.toFloat())
                view.draw(canvas)
                canvas.restore()
            }


        }
    }

XML 是(注意背景颜色以查看渲染区域):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_light">

    <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@android:color/holo_red_light"/>

</LinearLayout>

有了这个,我可以在每个 ViewHolder 之间扩展和定位我的 XML,但我仍然有两个大问题:

  1. 我的 TextView 被绘制在 ViewHolder 上,所以我在这里得到了重叠。如果这个“绘制”操作推动 ViewHolder,那就太好了。

  2. 即使我的自定义 XML 布局的宽度为“match_parent”,它也只包含文本视图。

如果可能的话,我想知道“度量”和“布局”到底是什么意思,以及它如何影响我的视图“区域”。以及如何防止重叠。

我“解决”了在画布上绘制文本的重叠问题,使用

Paint().apply {
    color = Color.BLACK
    style = Paint.Style.FILL
    textSize = 40f

    canvas.drawText(year.toString(), left.toFloat(), top.toFloat(), this)
}

但是由于我的布局有点复杂,所以很高兴了解如何使用 XML 布局来做到这一点。

谢谢

标签: androidandroid-layoutandroid-recyclerviewandroid-xmlitem-decoration

解决方案


推荐阅读