Get android's id resource from a string

2019-02-28 04:56发布

问题:

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

回答1:

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



回答2:

Another option allowing to declare your array with not-nullable ImageViews:

val imageViews : Array<ImageView> = Array(4, {
    val id: Int = resources.getIdentifier("imageView_" + it, "id", packageName)
    findViewById<ImageView>(id)
})


回答3:

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)
}