Kotlin中的动态视图

I am trying to create dynamic TextView by creating an array of TextViews but getting error :

java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
我的代码:
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])
    }
评论
DJHongKong
DJHongKong

When i is 0 what is the meaning of layout.addView(txtViews[i])?! Put 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])
        }
点赞
评论