Compose中切换LottieAnimation时无法重启的问题求助
解决LottieCompose切换动画时继承前进度的问题
你遇到的问题核心是:当通过Flow切换动画资源时,LottieAnimation内部的动画进度没有被重置,导致新动画从之前的进度继续播放而非从头开始。原因在于你看到的源码逻辑仅在播放状态从false切换到true时才会重置进度,但切换动画资源时播放状态一直是true,所以该条件不会触发。
这里提供两种可行的解决方案:
方案一:为LottieAnimation添加资源key
通过给LottieAnimation组件添加与动画资源绑定的key,当资源变化时,组件会完全重建,内部的动画状态也会从头初始化:
val composition by rememberLottieComposition(spec = LottieCompositionSpec.Asset(state.animation)) LottieAnimation( composition = composition, restartOnPlay = true, iterations = LottieConstants.IterateForever, key = state.animation // 绑定动画资源为key,资源变化时重建组件 )
方案二:手动监听composition变化并重置进度
使用LaunchedEffect监听composition的变化,当新的动画资源加载完成后,手动重置动画进度并启动播放:
val composition by rememberLottieComposition(spec = LottieCompositionSpec.Asset(state.animation)) val animatable = rememberLottieAnimatable() // 监听composition变化,重置并启动新动画 LaunchedEffect(composition) { composition ?: return@LaunchedEffect animatable.resetToBeginning() animatable.animate( composition = composition, iterations = LottieConstants.IterateForever ) } LottieAnimation( composition = composition, progress = animatable.progress )
这两种方案都能确保切换动画资源时,新动画从头开始无限循环播放。
内容的提问来源于stack exchange,提问作者hknhknhkn
相关产品推荐
相关产品推荐

