I have a requirement to display different images based on certain user interactions. So, I'm storing the drawable resource ID in an integer variable. However, when I pass this variable into the Image's painterResource function the image is not rendered.

Code looks like this:

val img = R.drawable.img1
val img2 = R.drawable.img2

// imageToDisplay is assigned based on certain conditions.
var imageToDisplay = img

Image(painter = painterResource(imageToDisplay), contentDescription = null)
1

There are 1 best solutions below

2
On BEST ANSWER

The code you provided is working "as it is" using available drawables in my end, unless you include more details then we can only guess, but when you said

I have a requirement to display different images based on certain user interactions. …

and

… imageToDisplay is assigned based on certain conditions.

and

… when I pass this variable into the Image's painterResource function the image is not rendered.

My best guess is the composable these codes are in is not re-composing or not updating for some reason when you perform some conditional action.

Again, we can only guess so you can try this or just use this as a reference.

@Composable
fun DynamicImageComposable() {

    val img = R.drawable.img
    val img2 = R.drawable.img

    // don't use ordinary variable, convert it to a mutable State instead
    var imageToDisplay by remember {
        mutableStateOf(img) // just use any drawable you want as the initial value
    }

    // when you change this to img2, this composable is expected to re-compose
    imageToDisplay = img

    Image(painter = painterResource(imageToDisplay), contentDescription = null)
}

The logic is a bit useless, but what its trying to point is using mutable state for a composable to re-compose.