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

cha*_*ait 8 android lottie android-jetpack-compose

在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?) {
        }
    })
Run Code Online (Sandbox Code Playgroud)

我们如何使用 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
    }
}
Run Code Online (Sandbox Code Playgroud)

ngl*_*ber 21

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.
}
Run Code Online (Sandbox Code Playgroud)

  • 但根据文档,下面的回调可用,但没有看到任何示例代码。https://airbnb.io/lottie/#/android-compose“访问错误、isLoading、isComplete、isFailure 和 isSuccess 属性。” (2认同)