We can change image by name using string interpolation in Swift. Is there a way to achieve this in Kotlin? Can we change selected image programatically in 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:
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? Can it be solved better?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.