Search code examples
androidkotlinandroid-jetpack-composeandroid-drawable

Kotlin Jetpack, How to load drawables using string array


I am loading images from drawables folder to the buttons with following code.

Icon(
    painter=painterResource(R.drawable.imageName),
    modifier=Modifier.size(30.dp),
    contentDescription="drawable icons",
    tint=Color.Unspecified
)

But I want to use that code in a loop with a string array such as

val imageNames = arrayOf("image1", "image2")

for (k in imageNames.indices) {
      Icon(
          painter=painterResource(R.drawable.imageNames[k]),
          modifier=Modifier.size(30.dp),
          contentDescription="drawable icons",
          tint=Color.Unspecified
       )
}        

Solution

  • Drawables should be drawable value resources not String in your case

    val imageNames = arrayOf("image1", "image2")
    

    Should be

    val imageRes = arrayOf(R.drawable.ic_1, R.drawable.ic_2)
    
    imageRes.forEach { res ->
         Icon(
             painter=painterResource(res),
             modifier=Modifier.size(30.dp),
             contentDescription="drawable icons",
             tint=Color.Unspecified
         )
    }
    

    But in case you want to make a mapping of image1 and image2 string values to your corresponding Drawables consider this,

    @Composable
    fun MyScreen() {
    
        val imageNames = arrayOf("image1", "image2")
    
        imageNames.forEach { imageString ->
            val imageRes = imageString.mapToMyImageResource()
    
            Icon(
                painter=painterResource(imageRes),
                modifier=Modifier.size(30.dp),
                contentDescription="drawable icons",
                tint=Color.Unspecified
            )
        }
    }
    
    @DrawableRes
    fun String.mapToMyImageResource() : Int =
        when (this) {
            "image1" -> {
                R.drawable.ic_1
            }
            "image2" -> {
                R.drawable.ic_2
            }
            else -> {
                R.drawable.ic_default
            }
        }