Reputation: 135
I'm working on an Android app using Jetpack Compose 1.0.0 and I'm trying to make a composable that uses a nullable image URL string and, if it's null, it will show a placeholder with painterResource
and, if it's not null, it will display the actual image using rememberImagePainter
.
The way I was doing that was:
@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)
}
Unfortunately, the rememberCoilPainter
became deprecated from accompanist-coil and it's suggested now to use the rememberImagePainter
. However, the ImagePainter.request
can't be changed like above. I then tried the following code:
@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)
}
But this doesn't work because painterResource
and rememberImagePainter
must be used on the @Composable
function. How can i achieve the same effect as before?
Upvotes: 8
Views: 12014
Reputation: 464
For Coil 2.2.+ It has remeberAsyncImagePainter instead off rememberImagePainter
Image(painter = rememberAsyncImagePainter(model = imageUrl,
imageLoader = ImageLoader.Builder(context).crossfade(true).build()),
contentDescription = "images")
Upvotes: 5
Reputation: 88102
In Coil 2.0.0 both AsyncImage
and rememberAsyncImagePainter
have placeholder
parameter that takes any other painter:
AsyncImage(
model = imageURL,
placeholder = painterResource(R.drawable.placeholder),
contentDescription = null,
)
In Coil 1.4.0 you can use builder
like this:
Image(
rememberImagePainter(
imageURL,
builder = {
placeholder(R.drawable.placeholder)
}
),
contentDescription = null,
)
Upvotes: 9