Home > front end >  Is there a way to get R.drawable.filename to change using a variable for filename?
Is there a way to get R.drawable.filename to change using a variable for filename?

Time:09-14

So I am creating a data class in kotlin that I would like to have a reference to a drawable resource, but there are ~40 different birds that the data class could be. What I am trying to do is have different birds that then will show a different picture depending on a bird number.

for example:

val bird = Bird(1) //where the 1 is the bird index in the file.
bird.updatevalues() // updates the bird data (name etc.)

//what I want to do is this:
R.drawable.(bird.getDrawableName)

Or is there a way to search the resources and find one that is called the same name as the bird and then I can just return the ID?

for example:

data class Bird(birdNumIn: Int){
    val birdNum = birdNumIn

    var birdName: String

    fun updateValues(){
        birdName = //name comes from CSV file.
    }

    fun searchDrawables(){
        //find the drawable resource corresponding to the birds name
}
val bird = Bird(1) //where the 1 is the bird index in the file.
bird.updatevalues() // updates the bird data (name etc.)

getDrawable(bird.searchDrawables()) //should get the photo 

If there is any other way that I have not thought about, please let me know. This problem has had me stumped for a while!

Thanks in Advance.

CodePudding user response:

Try this

int id = getResources().getIdentifier(drawableImageName, "drawable", getPackageName());

here drawableImageName is your dynamic image name.

  • Related