Articles I wrote earlier Code to paste to ImageView by specifying the image name as a character string (android)
I had LGTM for this, so I looked at it, but it was subtle, so I will rewrite it (in addition, with kotlin) There is a method in swift to set an image in ImageView from the resource name, but it is unlikely in kotlin.
By the way, in swift
imageView.image = UIImage(named:"hoge.png ")
You can set an image in imageView like this.
Let's reproduce something similar with kotlin.
StringExtensions.kt
fun String.getResourceId(context: Context): Int {
return context.resources.getIdentifier(this, "drawable", context.packageName)
}
I have defined an extension class for String
ImageViewExtensions.kt
fun ImageView.setImageResourceByName(name: String) {
this.setImageResource(name.getResourceId(context))
}
You have defined an extension for the ImageView class.
private fun setImage() {
val imageView = ImageView(this)
imageView.setImageResourceByName("some_image_name_string")
parent_view.addView(imageView)
}
ImageView is dynamically added to parent_view
If you write it like kotlin
private fun setImage() {
parent_view.addView(
ImageView(this).apply {
setImageResourceByName("some_image_name_string")
}
)
}
Is it like this? At first I thought it was hard to see, but I personally like it because the responsibility of "adding an image to parent_view" can be expressed as a whole.
swift
imageView.image = UIImage(named:"some_image_name_string.png ")
kotlin
imageView.setImageResourceByName("some_image_name_string")
I think it looks a lot like that. You can use it as it is by copying and pasting the two extensions of String and ImageView defined above.
Recommended Posts