Home > Back-end >  Kotlin Jetpack, How to load drawables using string array
Kotlin Jetpack, How to load drawables using string array

Time:11-04

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
       )
}        

CodePudding user response:

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
        }
    }

CodePudding user response:

@Composable
fun ImageList() {

//declare your list as resource types
val imagesNames = arrayOf(R.drawable.image1,R.drawable.image2)

Column {
    imageNames.forEach { image ->
       Icon(
               painter=painterResource(image),
               modifier=Modifier.size(30.dp),
               contentDescription="drawable icons",
               tint=Color.Unspecified
            )
     }
 }
}

Hope you found it helpful!

  • Related