Kotlin 中的动态视图数组

Dynamic array of views in Kotlin

我正在尝试通过创建 TextViews 的数组来创建动态 TextView,但出现错误:

java.lang.ArrayIndexOutOfBoundsException: length=0; index=0

My Code:

var txtViews = arrayOfNulls<TextView>(3)
    for (i in txtViews.indices) {
        txtViews = arrayOfNulls(i)
        txtViews[i]?.textSize = 24.0F
        txtViews[i]?.text = "Hello"
        txtViews[i]?.setTextColor(ContextCompat.getColor(this,
        R.color.colorAccent))
        layout.addView(txtViews[i])
    }

您从未在数组中初始化那些空引用:

这应该适用于您要实现的目标:

val txtViews = arrayOfNulls<TextView>(3)
        for (i in txtViews.indices) {
            txtViews[i] = TextView(context).apply {
                textSize = 24.0F
                text = "Hello"
                setTextColor(
                    ContextCompat.getColor(context,
                        R.color.colorAccent))
            }
            layout.addView(txtViews[i])
        }

There was no need to create arrayOfNulls

我是这样做的:

for (i in size) {
        val txtView = TextView(this).apply {
            textSize = 24.0F
            text = Html.fromHtml("&#8226")
            setTextColor(
                ContextCompat.getColor(
                    context,
                    R.color.colorAccent
                )
            )
        }

        layout.addView(txtView)
    }