我有一个要求,以显示基于某些用户交互不同的图像.因此,我将可绘制的资源ID存储在一个整数变量中.但是,当我将此变量传递给Image的painterResource函数时,不会呈现图像.

代码如下所示:

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)

推荐答案

您提供的代码在我这一端使用可用的可绘制程序时是"按原样"工作的,除非您包含更多的细节,我们只能猜测,但是当您说

我有一个要求,以显示基于某些用户交互不同的图像.…

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

这个逻辑有点无用,但它试图指出的是使用可变状态来重新组合可组合对象.

Android相关问答推荐

如何正确增加LazyStream中的变量

CameraX与jetpack组成屏幕逻辑

推断的类型是片段,但应为上下文

在命令行Android应用程序开发中苦苦挣扎

在Jetpack Compose中的隐藏状态栏后面绘制

从惰性列中删除项目时Jetpack Compose崩溃

如何在Jetpack Compose中创建这个圆形?

Android v31 及更低版本中 ImageView 中的圆角

Color.Transparent 和 Color.Unspecified 之间的区别

为什么 Android Studio 中的 theme.xml 目录没有任何原色

如何删除房间数据库?

我如何比较多个时间范围并在 Android Compose 中并排显示它们

根据另一个数组的值对数组进行排序

在移动设备上看到时如何增加 PasswordField 文本?

在事件中使用 Context/Toast 时不需要的重组 - Jetpack Compose

如何在行/列/卡片 compose 中添加左边框

重命名列失败的房间自动迁移(NOT NULL 约束失败,生成错误的迁移类)

firebase-messaging和firebase-inappmessaging-display之间有什么区别?

如何在stroke android drawable中设置渐变

多个项目 react-native android 构建错误