Get android's id resource from a string

人走茶凉 提交于 2019-12-31 04:48:47

问题


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


来源:https://stackoverflow.com/questions/46702479/get-androids-id-resource-from-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!