Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin Jetpack, How to load Icon images 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
                        )
              }        

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
        }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading