在我的 Android 应用程序中,我使用 Jetpack Compose 作为 UI。
在屏幕中,我使用从网址下载的lottie 文件来渲染图像。 Lottie 图像文件的渲染如下:
@Composable
private fun Image(assetUrl: String) {
val composition by rememberLottieComposition(LottieCompositionSpec.Url(assetUrl))
val progress by animateLottieCompositionAsState(composition, iterations = LottieConstants.IterateForever)
LottieAnimation(
composition = composition,
progress = { progress }
)
}
我想提供一个预览可组合方法,该方法也将渲染上面的
Image
可组合项。理想情况下,我希望能够做这样的事情:
@Preview
@Composable
private fun ScreenPreview(){
Theme {
Surface {
Screen(assetUrl = /* Some URL */)
}
}
}
例如,屏幕将是一些包含
Image
可组合项的可组合项:
@Composable
fun Screen(assetUrl: String){
Image(
assetUrl = assetUrl
)
}
问题:
不幸的是,Jetpack Compose 的 @Preview 注释不支持直接网络操作,例如从 URL 下载图像或 Lottie 文件。此限制是因为预览旨在静态渲染,而不执行网络请求或访问外部资源。
要解决此问题,您可以:
您可以将本地 Lottie 文件捆绑到应用程序的资源(原始文件夹)中,并将其用于预览。
例如:
将 Lottie 文件添加到 raw 文件夹 将 Lottie JSON 文件(例如 example.json)放置在 res/raw 目录中。
更新预览图像功能 为预览添加 defaultComposition 参数以使用本地资源:
@Composable
private fun Image(
assetUrl: String,
defaultComposition: LottieCompositionSpec? = null
) {
val composition by rememberLottieComposition(
defaultComposition ?: LottieCompositionSpec.Url(assetUrl)
)
val progress by animateLottieCompositionAsState(composition, iterations = LottieConstants.IterateForever)
LottieAnimation(
composition = composition,
progress = { progress }
)
}
定义预览可组合项
在预览中,提供本地合成而不是 URL:
@Preview
@Composable
private fun ScreenPreview() {
Theme {
Surface {
Screen(assetUrl = "") // URL is ignored in previews
}
}
}
@Composable
fun Screen(assetUrl: String) {
Image(
assetUrl = assetUrl,
defaultComposition = LottieCompositionSpec.RawRes(R.raw.example) // Use local file
)
}
如果您想在不使用真实 URL 的情况下模拟网络 Lottie 文件:
使用假数据进行预览 修改图像可组合项以检查它是否处于预览模式:
@Composable
private fun Image(
assetUrl: String
) {
val composition by rememberLottieComposition(
if (isInPreview()) {
LottieCompositionSpec.RawRes(R.raw.example) // Use local file
} else {
LottieCompositionSpec.Url(assetUrl) // Use URL at runtime
}
)
val progress by animateLottieCompositionAsState(composition, iterations = LottieConstants.IterateForever)
LottieAnimation(
composition = composition,
progress = { progress }
)
}
@Composable
fun isInPreview(): Boolean {
return LocalInspectionMode.current
}
现在,在预览中,图像可组合项将加载本地 Lottie 文件。