5

我正在使用 Jetpack Compose 1.0.0 开发一个 Android 应用程序,我正在尝试制作一个使用可为空的图像 URL 字符串的组合,如果它为空,它将显示一个占位符painterResource,如果它不为空,它将使用 显示实际图像rememberImagePainter

我这样做的方式是:

@Composable
fun VariableImagePainterExample (
    imageURL: String?
) {
    val painter = rememberCoilPainter(
        null,
        previewPlaceholder = R.drawable.ic_placeholder_user,
        fadeIn = true,
    )

    LaunchedEffect(imageURL) {
        painter.request = imageURL
    }

    Image(painter = painter, contentDescription = null)
}

不幸的是,rememberCoilPainter伴奏线圈已弃用,现在建议使用rememberImagePainter. 但是,ImagePainter.request不能像上面那样更改。然后我尝试了以下代码:

@Composable
fun VariableImagePainterExample (
    imageURL: String?
) {
    val painter = remember {
        mutableStateOf<ImagePainter>(painterResource(id = R.drawable.ic_placeholder_user))
    }

    LaunchedEffect(imageURL) {
        painter.value = rememberImagePainter(imageURL)
    }

    Image(painter = painter.value, contentDescription = null)
}

但这不起作用,因为painterResource并且rememberImagePainter必须在@Composable函数上使用。我怎样才能达到和以前一样的效果?

4

1 回答 1

5

您可以使用 set 占位符 using builder,如下所示:

val painter = rememberImagePainter(
    imageURL,
    builder = {
        placeholder(R.drawable.test)
    }
)
Image(
    painter,
    contentDescription = null,
)

不知道你为什么要换画家LaunchedEffect

于 2021-08-07T05:13:59.133 回答