android - 如何在 Jetpack Compose 中使用 Coil 显示自定义可组合占位符?
问题描述
我需要使用 Coil 在 Jetpack Compose 中显示一个自定义占位符,但该占位符不是可绘制的,它是我自定义的可组合函数。用线圈可以做到这一点吗?这是我使用线圈的代码片段:
Image(
modifier = Modifier
.size(120.dp)
.align(Alignment.CenterHorizontally),
painter = rememberImagePainter(
data = entry.imageUrl,
builder = {
crossfade(true)
MyPlaceholder(resourceId = R.drawable.ic_video)
},
),
contentDescription = entry.pokemonName
)
这是我的自定义占位符撰写功能:
@Composable
fun MyPlaceholder(@DrawableRes resourceId: Int) {
Surface(
modifier = Modifier.fillMaxSize(),
color = Color(0xFFE0E0E0)
) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center,
) {
Surface(
modifier = Modifier.size(30.dp),
shape = CircleShape,
color = Color.White
) {
Image(
modifier = Modifier
.padding(
PaddingValues(
start = 11.25.dp,
top = 9.25.dp,
end = 9.25.dp,
bottom = 9.25.dp
)
)
.fillMaxSize(),
painter = painterResource(id = resourceId),
contentDescription = null
)
}
}
}
}
我的gradle(线圈):
// Coil
implementation 'io.coil-kt:coil-compose:1.4.0'
解决方案
Coil 没有对可组合占位符的内置支持。
您可以将您的可组合放入其中并根据状态Box
显示占位符。Image
在我的示例中,如果状态为Loading
或,我将显示它Error
。您可以为案例添加另一个视图参数Error
并使用Crossfade
而不是AnimatedVisibility
.
我还添加Modifier.matchParentSize()
了Image
在修改器参数上计算的跟随父大小。您不能将修饰符参数直接传递给Image
,因为像这样的修饰符align
仅适用于直接子级,这就是为什么您总是必须将其传递给容器视图的原因。
@Composable
fun Image(
painter: ImagePainter,
placeholder: @Composable () -> Unit,
contentDescription: String?,
modifier: Modifier = Modifier,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Fit,
alpha: Float = DefaultAlpha,
colorFilter: ColorFilter? = null,
) {
Box(modifier) {
Image(
painter = painter,
contentDescription = contentDescription,
alignment = alignment,
contentScale = contentScale,
alpha = alpha,
colorFilter = colorFilter,
modifier = Modifier.matchParentSize()
)
AnimatedVisibility(
visible = when (painter.state) {
is ImagePainter.State.Empty,
is ImagePainter.State.Success,
-> false
is ImagePainter.State.Loading,
is ImagePainter.State.Error,
-> true
}
) {
placeholder()
}
}
}
用法:
Image(
painter = rememberImagePainter(imageUrl),
placeholder = {
CustomComposableView(...)
},
contentDescription = "...",
modifier = Modifier
...
)
推荐阅读
- ios - iOS/Swift 和 Coinbase Pro API - 订阅 Websocket 源
- webpack - Webpack Extract Text Plugin:如何测试特定文件并提取到单独的输出?
- javascript - HTML5画布游戏中的重力正在破坏我的碰撞
- javascript - 从 HTML 中调用单独的 Javascript 文件中的函数不起作用
- google-bigquery - 如何将存储中的字段插入 BigQuery 中的 SQL 查询
- c++ - 为什么 C++ 允许使用负索引和大于数组长度减 1 的索引进行索引?
- python - 按类型过滤电影- Python Movie Database
- javascript - Nightmare JS 点击基于 :contains
- vb6 - 数据查询不能作为 VB6 的 ADO 数据控件的 RecordSource
- python - 如何在 Python Clint 模块中创建自定义验证器