【问题标题】:Get android's id resource from a string从字符串中获取android的id资源
【发布时间】:2023-10-03 15:00:01
【问题描述】:
在我的 Kotlin 应用程序中,我有一些 ImageViews(在 activity_main.xml 中):imageView_0、imageView_1、imageView_2 和 imageView_3。
如何在从 0 到 3 的循环中访问视图?这行不通:
val imageView: ImageView = findViewById<ImageView>("R.id.imageView_" + index) as ImageView
【问题讨论】:
标签:
android
android-layout
imageview
kotlin
【解决方案1】:
for(i in 1..3){
val id: int=getResources().getIdentifier("imageview_"+i, "id",
getPackageName())
imageview[i]=findViewById(id) as ImageView
}
如果你在xml、imageview_1、imageview_2、imageview_3
【解决方案2】:
另一个选项允许使用不可为空的ImageViews 声明您的数组:
val imageViews : Array<ImageView> = Array(4, {
val id: Int = resources.getIdentifier("imageView_" + it, "id", packageName)
findViewById<ImageView>(id)
})
【解决方案3】:
我最终这样做了:
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)
}