从字符串中获取Android的ID资源

3
在我的 Kotlin 应用程序中,我有一些 ImageView(在 activity_main.xml 中):imageView_0、imageView_1、imageView_2 和 imageView_3。
我如何在循环中访问从 0 到 3 的视图?这样是行不通的:
val imageView: ImageView = findViewById<ImageView>("R.id.imageView_" + index) as ImageView
3个回答

8
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,请参考以下操作:

2

另一种选项是使用非空的 ImageView 声明数组:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接