Search code examples
androidkotlindrawable

Get drawable resource by identifier Kotlin


Hi I'm android studio noob, I'm trying to get an image from the drawable resources by giving the identifier like this:

enter image description here

The "val s" is dynamic variable so in every cicle of the for it will be different.

It is working fine but the code seems to be obsolete. Do you have any idea how could I do this same functionality without been obsolete? Also I want to set this image into a dynamic button.

Thank you so much


Solution

  • You can use this method.

        val s = "ico_btn_menu_terminal"
        val d = resources.getDrawable(this.resources.getIdentifier(s, "drawable", this.packageName), null)
        button_dynamic.background = d
    

    so you can use getDrawable(id, theme) instead getDrawable(id) method. and you can use .background instead setBackgroundDrawable method.