Integrating Lottie Animations in Jetpack Compose

Lottie is a popular animation library developed by Airbnb that allows you to render After Effects animations natively on Android, iOS, and the web. Integrating Lottie animations into your Jetpack Compose applications can add delightful visual enhancements with minimal overhead. This post will guide you through integrating Lottie animations in Jetpack Compose, providing code samples and best practices.

What are Lottie Animations?

Lottie is a JSON-based animation file format that is exported from Adobe After Effects using the Bodymovin plugin. It enables designers to create intricate animations and ship them as lightweight, scalable vector graphics that can be rendered across different platforms.

Why Use Lottie Animations in Jetpack Compose?

  • Enhanced User Experience: Lottie animations add visual flair to your app.
  • Lightweight and Scalable: JSON-based animations are small in size and scale well across different screen densities.
  • Cross-Platform Compatibility: The same animation can be used on Android, iOS, and the web.
  • Easy to Implement: Lottie libraries provide simple APIs to load and control animations.

How to Integrate Lottie Animations in Jetpack Compose

To integrate Lottie animations in Jetpack Compose, follow these steps:

Step 1: Add Dependencies

Add the necessary Lottie Compose dependency in your build.gradle file:

dependencies {
    implementation("com.airbnb.android:lottie-compose:6.3.0")
}

Make sure to use the latest version available.

Step 2: Create a Lottie Animation JSON File

Create your animation in Adobe After Effects and export it as a JSON file using the Bodymovin plugin. Place the JSON file in the src/main/assets directory of your Android project. If the assets directory does not exist, create it.

Step 3: Implement Lottie Animation in Compose

Use the LottieAnimation composable to render the animation in your Jetpack Compose UI.


import androidx.compose.runtime.*
import androidx.compose.ui.tooling.preview.Preview
import com.airbnb.lottie.compose.*
import androidx.compose.foundation.layout.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.Alignment
import androidx.compose.ui.unit.dp
import androidx.compose.material3.Card

@Composable
fun LottieAnimationExample() {
    // Remember the composition to avoid recreation on recomposition
    val composition by rememberLottieComposition(
        LottieCompositionSpec.Asset("animations/loading.json") // Replace with your file name
    )

    // Animation properties
    val progress by animateLottieCompositionAsState(
        composition = composition,
        iterations = LottieConstants.IterateForever, // Repeat animation infinitely
        isPlaying = true // Start playing automatically
    )

    Card(modifier = Modifier
        .padding(16.dp)
        .fillMaxWidth()) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            LottieAnimation(
                composition = composition,
                progress = progress,
                modifier = Modifier.size(200.dp)
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
fun LottieAnimationExamplePreview() {
    LottieAnimationExample()
}

Explanation:

  • rememberLottieComposition: This composable loads the Lottie animation from the assets directory. It returns a LottieComposition, which is a parsed representation of your JSON file. The `remember` function ensures that the composition is loaded only once, and retained across recompositions.
  • LottieCompositionSpec.Asset("animations/loading.json"): Specifies the location of your Lottie animation file in the assets folder.
  • animateLottieCompositionAsState: This composable creates an animation state that allows you to control the playback of your animation. In this example, the animation plays infinitely.
  • composition: Passes the loaded LottieComposition.
  • iterations: Set to LottieConstants.IterateForever for infinite looping, or set a specific number for a finite loop.
  • isPlaying: Indicates whether the animation is playing. It’s set to true by default.
  • LottieAnimation: This composable renders the Lottie animation on the screen.
  • composition: Passes the loaded LottieComposition to the animation.
  • progress: Drives the animation by using the animated progress state.
  • modifier: Allows you to modify the size and other attributes of the animation.

Step 4: Handling Different Animation Playback Options

You can customize the animation behavior using different parameters:


import androidx.compose.runtime.*
import androidx.compose.ui.tooling.preview.Preview
import com.airbnb.lottie.compose.*
import androidx.compose.foundation.layout.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.Alignment
import androidx.compose.ui.unit.dp
import androidx.compose.material3.Card

@Composable
fun ControlledLottieAnimation() {
    val composition by rememberLottieComposition(
        LottieCompositionSpec.Asset("animations/success.json")
    )

    // Mutable state to control animation play state
    var isPlaying by remember { mutableStateOf(true) }

    val progress by animateLottieCompositionAsState(
        composition = composition,
        isPlaying = isPlaying, // Use the mutable state
        restartOnPlay = false, // Don't restart the animation on recomposition
        iterations = 1 // Play animation once
    )

    Card(modifier = Modifier
        .padding(16.dp)
        .fillMaxWidth()) {

        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            LottieAnimation(
                composition = composition,
                progress = progress,
                modifier = Modifier.size(200.dp)
            )

            //Button to toggle play/pause
            androidx.compose.material3.Button(onClick = { isPlaying = !isPlaying }) {
                androidx.compose.material3.Text(text = if (isPlaying) "Pause" else "Play")
            }

        }
    }

}

@Preview(showBackground = true)
@Composable
fun ControlledLottieAnimationPreview() {
    ControlledLottieAnimation()
}

Explanation:

  • Control Playback State: Using mutableStateOf, you can control the play/pause state of the animation with a button.
  • restartOnPlay: By setting this parameter to false, the animation doesn’t restart from the beginning every time it’s played after being paused.
  • Finite Iteration: iterations = 1 will play the animation once.

Best Practices for Using Lottie Animations in Compose

  • Optimize JSON Files: Minimize the size of your Lottie JSON files by removing unnecessary layers and elements in After Effects.
  • Asynchronous Loading: Use rememberLottieComposition to load the animation asynchronously and cache it to prevent performance bottlenecks.
  • Control Animation State: Manage the animation playback state effectively, especially in interactive UIs, using animateLottieCompositionAsState and mutable state variables.
  • Error Handling: Implement error handling to gracefully handle cases where the animation file is missing or corrupted.
  • Accessibility: Provide alternative descriptions for animations to ensure accessibility for users with disabilities.

Conclusion

Integrating Lottie animations in Jetpack Compose is a straightforward process that can greatly enhance the visual appeal and user experience of your Android applications. By following the steps and best practices outlined in this guide, you can seamlessly add beautiful, lightweight animations to your Compose UI, creating engaging and interactive experiences for your users.