You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose @Preview中LottieAnimation无法显示问题求助

Jetpack Compose预览中LottieAnimation无法显示的解决方案

问题背景

在Jetpack Compose的@Preview函数中使用LottieAnimation时,动画无法显示,但真实设备上运行完全正常。相关代码如下:

@Preview
@Composable
fun LottiePreview() {
    MaterialTheme {
        Surface {
            Column {
                Text(text = "Above lottie")

                val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.no_receipts))
                LottieAnimation(
                    composition = composition,
                )
                
                Text(text = "Below lottie")
            }
        }
    }
}

尝试调整多种设置和构造方法后仍无法解决,以下是几个可行的解决细节:


解决方法

1. 预览环境下同步加载Lottie资源

Compose预览的异步加载机制可能无法等待Lottie合成物加载完成,可在预览中使用同步加载方式(仅用于预览,真机保留异步逻辑):

@Preview
@Composable
fun LottiePreview() {
    MaterialTheme {
        Surface {
            Column {
                Text(text = "Above lottie")

                val composition = remember {
                    LottieCompositionFactory.fromRawResSync(LocalContext.current, R.raw.no_receipts)
                }.value
                
                composition?.let {
                    LottieAnimation(composition = it)
                }
                
                Text(text = "Below lottie")
            }
        }
    }
}

2. 添加加载状态判断

通过判断合成物的加载状态,确保动画仅在资源加载完成后显示,同时预览时能看到加载提示:

@Preview
@Composable
fun LottiePreview() {
    MaterialTheme {
        Surface {
            Column {
                Text(text = "Above lottie")

                val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.no_receipts))
                val progress by animateLottieCompositionAsState(composition)
                
                if (composition == null) {
                    Text(text = "Loading Lottie...")
                } else {
                    LottieAnimation(
                        composition = composition,
                        progress = { progress }
                    )
                }
                
                Text(text = "Below lottie")
            }
        }
    }
}

3. 检查预览设置与版本兼容性

  • 打开Android Studio的Compose预览设置,勾选Enable interactive preview和Use hardware acceleration,硬件加速能解决部分渲染问题
  • 确保lottie-compose版本与Jetpack Compose版本匹配,例如Compose 1.5.x对应Lottie Compose 6.0.0+版本

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:10:23