How to show a custom composable placeholder using Coil in Jetpack Compose?(如何在Jetpack Compose中使用线圈显示自定义可合成占位符?)
本文介绍了如何在Jetpack Compose中使用线圈显示自定义可合成占位符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在使用Coil编写Jetpack中显示自定义占位符,但该占位符不是可绘制的,它是我自定义的可组合函数。有没有可能用线圈做到这一点? 这是我使用Coil:的代码片段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
)
}
}
}
}
我的奖杯(线圈):
// 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
...
)
这篇关于如何在Jetpack Compose中使用线圈显示自定义可合成占位符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何在Jetpack Compose中使用线圈显示自定义可合成占位符?


基础教程推荐
猜你喜欢
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01