简体   繁体   English

使用字符串插值更改 Android 工作室 Kotlin 中的 imageView 资源?

[英]Using string interpolation to change imageView resource in Android studio Kotlin?

We can change image by name using string interpolation in Swift.我们可以使用 Swift 中的字符串插值按名称更改图像。 Is there a way to achieve this in Kotlin?有没有办法在 Kotlin 中实现这一点? Can we change selected image programatically in Kotlin?我们可以在 Kotlin 中以编程方式更改所选图像吗?

let image = UIIMage(named : "\(imageName)_selected")

You can:你可以:

val resourceId = resources.getIdentifier("${imagename}_selected", "drawable", packageName)

Personally, I'd go for a solution like this:就个人而言,我会 go 获得这样的解决方案:

val resourceId = when (imageName) {
    "image1" -> R.drawable.image1_selected
    "image2" -> R.drawable.image2_selected
}

Although this is a little bit longer, it gives compile time warnings and errors, assuring you the drawable is there.虽然这有点长,但它会给出编译时警告和错误,确保您可以绘制可绘制对象。

Perhaps the question is: why are you getting the string imageName?也许问题是:你为什么要得到字符串 imageName? Can it be solved better?能不能更好的解决?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM