【发布时间】:2021-09-06 23:08:15
【问题描述】:
我试图在 LazyRow 可组合中加载多个图像,painter state 总是给我一个 empty state,我不知道是什么我失踪了。
可组合的代码
fun NetworkImage(
url: String,
contentDescription: String = "",
modifier: Modifier,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Fit,
alpha: Float = DefaultAlpha,
colorFilter: ColorFilter? = null,
placeholderDrawableRes: Int? = null,
crossFade: Int? = null,
transformations: List<Transformation>? = null,
onLoading: @Composable () -> Unit,
onError: @Composable () -> Unit
) {
Box(
modifier = modifier
){
val painter = rememberImagePainter(
data = url,
builder = {
placeholderDrawableRes?.let {
placeholder( drawableResId = it )
}
error(
R.drawable.ic_warning
)
crossFade?.let {
crossfade(durationMillis = it)
}
transformations?.let {
transformations(transformations = it)
}
}
)
val imageState = painter.state
if(imageState is ImagePainter.State.Loading){
onLoading()
}
if(imageState is ImagePainter.State.Error){
onError()
}
Image(
painter = painter,
contentDescription = contentDescription,
contentScale = contentScale,
alignment = alignment,
alpha = alpha,
colorFilter = colorFilter
)
}
}
LazyRow
LazyRow(modifier = modifier) {
items(items = urls){ url ->
NetworkImage(
url = url,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize(),
onLoading = {
ConstraintLayout(
modifier = Modifier.fillMaxSize()
) {
val indicator = createRef()
CircularProgressIndicator(
modifier = Modifier.constrainAs(indicator) {
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
)
}
},
onError = {
Icon(
painter = painterResource(id = R.drawable.ic_warning),
contentDescription = "",
tint = Color.Red
)
}
)
}
}
当我使用 NetworkImage Composable 时,它只能正常工作一次,但是当我在 loop 或 LazyRow 中使用它时,它会呈现一个空盒子。 任何提示。
【问题讨论】:
-
@PhilipDukhov 这解决了在 builder 中使用
size(OriginalSize)时的问题。非常感谢。
标签: android kotlin android-jetpack-compose coil