androidandroid-jetpack-composelottie

How to use animation listener for Lottie animation in Android Jetpack Compose?


In Android View System, We can use animation listener like below to get lottie animation callbacks.

 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?) {
        }
    })

How we can add listener using Jetpack Compose? i added below code currently to play the lottie animation. I want to receive the callback after animation play completed.

@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
    }
}

Solution

  • Updated answer to version 1.0.0-rc01-1 of Lottie.

    What you can do is:

    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.
    }