Reputation: 4514
I am trying to create dynamic TextView
by creating an array of TextViews
but getting error :
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])
}
Upvotes: 1
Views: 3978
Reputation: 4514
There was no need to create arrayOfNulls
I did this way:
for (i in size) {
val txtView = TextView(this).apply {
textSize = 24.0F
text = Html.fromHtml("•")
setTextColor(
ContextCompat.getColor(
context,
R.color.colorAccent
)
)
}
layout.addView(txtView)
}
Upvotes: 0
Reputation: 2859
You never initialized those null references inside your array:
This should work for what you are trying to achieve:
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])
}
Upvotes: 2