2

I currently am working on an app that has a list of characters and images associated with each of them.

I want to insert images for all the characters using a for loop without actually hardcoding their image names:

Example:

var agentsList = listOf(
        "Astra",
        "Breach",
        "Brimstone",
        "Chamber",
        "Cypher",
        "Jett",
        "KAY/O",
        "Killjoy",
        "Neon",
        "Omen",
        "Phoenix",
        "Raze",
        "Reyna",
        "Sage",
        "Skye",
        "Sova",
        "Viper",
        "Yoru"
    )
for (agent in agentsList) {
    dataList.add(DataModel(agent, R.drawable.agent)
}

Here , R.drawable.agent is where I want to insert the images , but i want the for loop to do it for me using the string resource in agentsList.

I have saved the image using the same strings as the characters in agentsList, so that won't be an issue.

Sergio
  • 27,326
  • 8
  • 128
  • 149

1 Answers1

1

You can use string name to get drawable resource identifier:

for (agent in agentsList) {
    val resources: Resources = context.resources
    val resourceId: Int = resources.getIdentifier(agent, "drawable", context.packageName)
    dataList.add(DataModel(agent, resourceId)
}
Sergio
  • 27,326
  • 8
  • 128
  • 149