从字符串中获取android的id资源

时间:2017-10-12 06:03:14

标签: android android-layout imageview kotlin

在我的Kotlin应用中,我有一些ImageViews activity_main.xml ):imageView_0imageView_1imageView_2和{ {1}}。

如何在0到3的循环中访问视图?这不会起作用:

imageView_3

3 个答案:

答案 0 :(得分:7)

for(i in 1..3){
  val id: int=getResources().getIdentifier("imageview_"+i, "id", 
  getPackageName())
  imageview[i]=findViewById(id) as ImageView
}

如果您有 xml imageview_1imageview_2imageview_3

答案 1 :(得分:2)

允许使用不可为空的ImageView s声明数组的另一个选项:

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

答案 2 :(得分:0)

我最终这样做了:

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