您提供的代码在我这一端使用可用的可绘制程序时是"按原样"工作的,除非您包含更多的细节,我们只能猜测,但是当您说
我有一个要求,以显示基于某些用户交互不同的图像.…
和
…ImageToDisplay是根据特定条件分配的.
和
…当我将此变量传递给Image的painterResource函数时,不会呈现图像.
我最好的猜测是,当您执行某些条件操作时,这些代码所在的可组合代码不会重新组合或由于某种原因不会更新.
再说一次,我们只能猜测,所以你可以试一试,或者只是把它作为参考.
@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)
}
这个逻辑有点无用,但它试图指出的是使用可变状态来重新组合可组合对象.