简体   繁体   中英

Get android's id resource from a string

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM