In my Kotlin app I have some ImageViews
(in activity_main.xml
): imageView_0
, imageView_1
, imageView_2
and imageView_3
.
How can I access the view in a loop from 0 to 3? This won't work:
val imageView: ImageView = findViewById<ImageView>("R.id.imageView_" + index) as ImageView
for(i in 1..3){
val id: int=getResources().getIdentifier("imageview_"+i, "id",
getPackageName())
imageview[i]=findViewById(id) as ImageView
}
If you have in the xml
, imageview_1
, imageview_2
, imageview_3
Another option allowing to declare your array with not-nullable ImageView
s:
val imageViews : Array<ImageView> = Array(4, {
val id: Int = resources.getIdentifier("imageView_" + it, "id", packageName)
findViewById<ImageView>(id)
})
I ended up doing this:
var imageViews: Array<ImageView?> = arrayOfNulls(4)
for (i in 0..3) {
val id: Int = getResources().getIdentifier("imageView_" + i, "id", getPackageName())
imageViews.set(i, findViewById<ImageView>(id) as ImageView)
}