如何在Android Jetpack Compose中使用Lottie动画的动画监听器?

7
在 Android 视图系统中,我们可以使用以下方式的动画监听器来获取 Lottie 动画回调。
 playView = LottieAnimationView(this)
 playView.addAnimatorListener(object : Animator.AnimatorListener {
        override fun onAnimationStart(animation: Animator?) {
        }

        override fun onAnimationEnd(animation: Animator?) {
           
        }

        override fun onAnimationCancel(animation: Animator?) {
        }

        override fun onAnimationRepeat(animation: Animator?) {
        }
    })

我们如何使用Jetpack Compose添加监听器?我目前已添加以下代码以播放lottie动画。我希望在动画播放完成后接收回调。
@Composable
fun PlayView() {
    val animationSpec = remember { LottieAnimationSpec.RawRes(R.raw.play_anim) }
    val result: LottieCompositionResult by remember { mutableStateOf(LottieCompositionResult.Loading) }
    val context = LocalContext.current
    LottieAnimation(
        animationSpec,
        modifier = Modifier
            .fillMaxHeight()
            .fillMaxWidth()
    )

    if (result is LottieCompositionResult.Success) {
        //start the next flow
    }
}
1个回答

19

更新答案到 Lottie 版本 1.0.0-rc01-1

您可以进行以下操作:

val composition by rememberLottieComposition(
    LottieCompositionSpec.RawRes(R.raw.your_lottie_file)
)
val progress by animateLottieCompositionAsState(composition)

LottieAnimation(
    composition,
    modifier = Modifier
        .size(200.dp)
        .background(Color.Black),
) 

if (progress == 1.0f) {
    // Animation completes.
}

1
看起来在最新版本中,上述代码将无法工作。他们在LottiAnimation()中删除了animationState参数。 - Chait
2
但是根据文档,下面的回调可用,但没有看到任何示例代码。 https://airbnb.io/lottie/#/android-compose "访问错误、isLoading、isComplete、isFailure 和 isSuccess 属性。" - Chait
我猜他们没有实现像 lottieProgressAsState 这样的东西。 - MohammadBaqer
ths,这段代码现在在最新版本中可以正常工作。"progress"是一个状态,在动画完成后,compose函数将会执行它。 - JeckOnly

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接