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)
CodePudding user response:
One way to solve this issue is to use the resources property of the Image component to access the drawable resources. You can then use the getDrawable function to retrieve the drawable based on the resource ID stored in the imageToDisplay variable.
Here is an example of how your code can be modified to accomplish this:
val img = R.drawable.img1
val img2 = R.drawable.img2
// imageToDisplay is assigned based on certain conditions.
var imageToDisplay = img
Image(painter = painterResource(resources.getDrawable(imageToDisplay)), contentDescription = null)
Alternatively, you can also use the imageResource function instead of painterResource to set the drawable resource for the Image component. The code would look like this:
val img = R.drawable.img1
val img2 = R.drawable.img2
// imageToDisplay is assigned based on certain conditions.
var imageToDisplay = img
Image(imageResource = imageToDisplay, contentDescription = null)
CodePudding user response:
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.