David Zomada
David Zomada

Reputation: 157

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

Upvotes: 0

Views: 1134

Answers (3)

Darío Pm
Darío Pm

Reputation: 159

I think, nowadays (2023), using Kotlin, you should do:

binding.ViewToChangeImage.setImageResource(android.R.drawable.presence_online)

Upvotes: 0

King Of The Jungle
King Of The Jungle

Reputation: 745

I know this is late but just in case someone wants to accomplish the same with JetPack Compose, this is how you do it.

val s = "ico_btn_menu_terminal"
val context = LocalContext.current
val d by remember(s) {
        derivedStateOf {
            context.resources.getIdentifier(s, "drawable", context.packageName)
        }
    }
Image(
        painter = painterResource(id = d),
        contentDescription = "image"
    )

You might decide to remove the derivedStateOf depending on your use case.

Upvotes: 0

Daniel.Wang
Daniel.Wang

Reputation: 2496

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.

Upvotes: 3

Related Questions