我试图在LazyRow可组合中加载多个图像,画家状态总是给我一个空状态,我不知道缺少什么。
可组合代码
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 一次它可以正常工作时,但是当我在循环或LazyRow中使用它时,它会呈现一个空框。任何提示。