从一个字符串获取Android的ID资源

在我的Kotlin应用程序中,我有一些ImageViews (在activity_main.xml ): imageView_0imageView_1imageView_2imageView_3

我如何从0到3循环访问视图? 这不会起作用:

 val imageView: ImageView = findViewById("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 } 

如果你有在xmlimageview_1imageview_2imageview_3

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

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

我结束了这样做:

 var imageViews: Array = arrayOfNulls(4) for (i in 0..3) { val id: Int = getResources().getIdentifier("imageView_" + i, "id", getPackageName()) imageViews.set(i, findViewById(id) as ImageView) }