Get an image as a character string (resource name) and paste it into ImageView (kotiln)

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.

Get resourceId from string

StringExtensions.kt


fun String.getResourceId(context: Context): Int {
    return context.resources.getIdentifier(this, "drawable", context.packageName)
}

I have defined an extension class for String

Set the image in ImageView

ImageViewExtensions.kt


fun ImageView.setImageResourceByName(name: String) {
    this.setImageResource(name.getResourceId(context))
}

You have defined an extension for the ImageView class.

Example of use

    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.

Comparison with swift

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

Get an image as a character string (resource name) and paste it into ImageView (kotiln)
Code to specify the image name as a character string and paste it into ImageView (android)
Memorandum No.4 "Get a character string and decorate it" [Java]
[Android development] Get an image from the server in Java and set it in ImageView! !!