如何将自定义XML布局添加到自定义ItemDecoration中?

时间:2019-04-16 09:49:38

标签: android android-layout android-recyclerview android-xml item-decoration

我希望在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布局。

谢谢

0 个答案:

没有答案