Blog Infos
Author
Published
Topics
Published

The article focuses on two main points. First point is using Lottie Animation in Jetpack Compose. Other point is Managing Lottie Animation according to a business logic.

The story has a GitHub project. You can follow the topic commit by commit: https://github.com/canerkaseler/lottie-animation-jetpack-compose

Table of contents:

A) Using Lottie animation in Jetpack Compose:
  1. Add Lottie Animation and Dependencies into Android project
  2. Show Lottie Animation in Compose
  3. Show Specific Range of Lottie Animation in Compose
B) Managing Lottie animation in Compose:
  1. Stop Lottie Animation and show Success step in Compose
  2. Restart Lottie Animation in Compose
  3. Stop Lottie Animation and show Failure step in Compose

Final output will be this:

You can check it on master branch.

A) Part 1/3 — Add Lottie Animation and Dependencies into Android project

Firstly, I created a new Android project with Android Studio Giraffe 🦒 version. Also, I selected gradle type as KTS (Kotlin-Type-Script):

This project uses gradle as Kotlin Domain Specific Language.

So, project will appear like below. I used New UI of Android Studio. However, gradle files have to be “.kts”:

Fresh project.

Related commit in here.

To implement Lottie dependencies, please add this into the settings.gradle.kts file:

maven(url = "https://oss.sonatype.org/content/repositories/snapshots/")

Secondly, please add this into the app/build.gradle.kts file:

implementation("com.airbnb.android:lottie-compose:6.0.1")

Related commit in here.

Note: Please check latest version of Lottie compose in here.

Lastly, where should we put our Lottie Animation file into an Android project?

Please, select Android view, then right-click on “res” folder. Then, select “New/Folder/Raw-Resource-Folder” like below:

Raw folder creating.

Now, you should have “raw” folder under your “res” folder. So, your Android project structure should appear like this:

Project structure

Note: I assume you already have a Lottie animation file as “.json” format. My GitHub repository has one but if you want to have different one, you can download it from here.

You can put your “.json” format Lottie Animation file, under your “raw” folder. Current, you can find Lottie file in the project:

Lottie animation json file in android project.

Related commit in here.

Well done! You are ready to show Lottie animation in Compose 👏

A) Part 2/3 — Show Lottie Animation in Compose

In this part, you already have Lottie implementation in Android Project and Lottie animation as “.json” file. Let’s show Lottie animation in jetpack compose!

Here is related GitHub commit about adding Lottie animation.

To show Lottie animation in Jetpack Compose UI, you need to use LottieAnimation function from library:

import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.rememberLottieComposition

@Composable
fun ComposeLottieAnimation(modifier: Modifier) {

    val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.anim_loading_success_failed))

    LottieAnimation(
        modifier = modifier,
        composition = composition,
        iterations = LottieConstants.IterateForever,
    )
}

In this step, you can see Lottie animation will play forever because of “LottieConstants.IterateForever”.

We should see full Lottie animation which is Loading > Success > Loading > Failure. Let’s what we have:

Full animation is Loading > Success > Loading > Failure.

Job Offers

Job Offers

There are currently no vacancies.

OUR VIDEO RECOMMENDATION

, ,

Migrating to Jetpack Compose – an interop love story

Most of you are familiar with Jetpack Compose and its benefits. If you’re able to start anew and create a Compose-only app, you’re on the right track. But this talk might not be for you…
Watch Video

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer for Jetpack Compose
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engin ...
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer f ...
Google

Jobs

Great! You are ready for more specific Lottie settings in Compose 👏

A) Part 3/3 — Show Specific Range of Lottie Animation in Compose

LottieAnimation has clipSpec parameter. Therefore, we can play specific range of the animation. For this, we need to use “LottieClipSpec.Progress(min, max)” function.

Here is related GitHub commit about range of Lottie animation.

In below example, I selected specific range for Lottie animation:

import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieClipSpec
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.rememberLottieComposition

@Composable
fun ComposeLottieAnimation(modifier: Modifier) {

    val clipSpecs = LottieClipSpec.Progress(0.2f, 0.5f)

    val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.anim_loading_success_failed))

    LottieAnimation(
        modifier = modifier,
        composition = composition,
        iterations = LottieConstants.IterateForever,
        clipSpec = clipSpecs,
    )
}

Lottie animation should play only between loading and success:

Perfect! You completed Lottie animation in Compose 👏

Let’s move forward 🚀

B) Part 1/3 — Stop Lottie Animation and show Success step in Compose

In this part, we would like to show loading animation during waiting. However, when waiting is finished, we would like to move success checkmark part of the animation. Also, animation should stop.

Here is related GitHub commit.

For this business logic, I added Successful button to stop animation as completed. Firstly, let’s look at animation function:

@Composable
fun ComposeLottieAnimation(modifier: Modifier, isCompleted: Boolean) {

    val clipSpecs = LottieClipSpec.Progress(
        min = 0.0f,
        max = if (isCompleted) 0.44f else 0.282f
    )

    val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.anim_loading_success_failed))

    LottieAnimation(
        modifier = modifier,
        composition = composition,
        iterations = if (isCompleted) 1 else LottieConstants.IterateForever,
        clipSpec = clipSpecs,
    )
}

You can see isCompleted as parameter. It helps to manage max value of animation progress. Why do we not change min value? Because, this Lottie animation progress is Loading > Success > Loading > Failure.

Note: If we change min value, start point of animation changes. We will do this in other part.

Also, we change Iterations as 1 to play once success animation.

Lastly, I would like to show calling “ComposeLottieAnimation()” function in compose:

@Composable
fun ComposeLottieScreen() {

    var isSuccess by remember { mutableStateOf(false) }

    Box(modifier = Modifier
        .fillMaxSize()
        .background(color = Color.White)
    ){
        ComposeLottieAnimation(
            modifier = Modifier.align(alignment = Alignment.Center),
            isCompleted = isSuccess
        )

        Button(
            modifier = Modifier.align(alignment = Alignment.BottomCenter).padding(bottom = 45.dp),
            onClick = { isSuccess = true }
        ) {
            Text(
                text = "Successful"
            )
        }
    }
}

The most important point is isSuccess variable. It can keep it’s latest boolean value in recomposition because of remember keyword. Button clicking is changing value of isSuccess.

To sum up, we have business logic on Lottie animation in Jetpack Compose:

Loading > Success then stop animation.

Nice start! You completed first business logic with Lottie animation in Compose 👏

B) Part 2/3 — Restart Lottie Animation in Compose

Loading animation should play during waiting. Then, when waiting is finished (clicking Successful button), we would like to move success checkmark part of the animation. It should stop until restarting. When we click restart, animation should start from loading part.

Here is related GitHub commit.

If you did not yet check “B) Part 1/3”, please check it. The reason is that code already has Success logic as Completion. Thus, we just need to change mutable value:

var isSuccess by remember { mutableStateOf(false) }

// Restart button.
Button(
    modifier = Modifier
        .align(alignment = Alignment.CenterHorizontally)
        .padding(bottom = 45.dp),
    onClick = { 
        isSuccess = false // Restart animation.
    }
) {
    Text(
        text = "Restart"
    )
}

As you can see, clicking restart button restart animation from loading state:

Loading > Success > Restart > Loading …

Good job! You added second business logic with Lottie animation in Compose 👏

Do not give up! Last part is a milestone 🪐

B) Part 3/3 — Stop Lottie Animation and show Failure step in Compose

In this final step, Lottie animation should play in loading state until getting success or failure. When the animation gets one of them, animation should move related step such as Success checkmark or Failure cancel, then has to stop. Moreover, animation has to come back loading step with clicking reset button.

Here is related GitHub commit.

Previously, we had only one state for completion which is Success. Now, we need to consider about Failure.

@Composable
fun ComposeLottieScreen() {

    var isSuccess by remember { mutableStateOf(false) }
    var isFailed by remember { mutableStateOf(false) }

    Box(modifier = Modifier
        .fillMaxSize()
        .background(color = Color.White)
    ){
        ComposeLottieAnimation(
            modifier = Modifier.align(alignment = Alignment.Center),
            isSuccess = isSuccess,
            isFailed = isFailed
        )

        Column(
            modifier = Modifier.align(Alignment.BottomCenter)
        ) {

            // Successful button.
            Button(
                modifier = Modifier
                    .align(alignment = Alignment.CenterHorizontally)
                    .padding(bottom = 15.dp),
                onClick = {
                    isSuccess = true
                    isFailed = false
                }
            ) {
                Text(
                    text = "Successful"
                )
            }

            // Failure button.
            Button(
                modifier = Modifier
                    .align(alignment = Alignment.CenterHorizontally)
                    .padding(bottom = 15.dp),
                onClick = {
                    isFailed = true
                    isSuccess = false
                }
            ) {
                Text(
                    text = "Failure"
                )
            }

            // Restart button.
            Button(
                modifier = Modifier
                    .align(alignment = Alignment.CenterHorizontally)
                    .padding(bottom = 45.dp),
                onClick = {
                    isSuccess = false
                    isFailed = false
                }
            ) {
                Text(
                    text = "Restart"
                )
            }
        }
    }
}

According to states, we have to get change start and stop durations of the animation with iteration.

Previously, I mentioned in “B) Part 1/3 — Note”. Now, we have to change min value of animation because failure part of the animation plays after success part. Because of the reason, we have to start animation after success time.

In below code, you can see that if “isFailed” is true, animation start from 0.49 which is after success duration (0.44):

@Composable
fun ComposeLottieAnimation(modifier: Modifier, isSuccess: Boolean, isFailed: Boolean) {

    val clipSpecs = LottieClipSpec.Progress(
        min = if (isFailed) 0.499f else 0.0f,
        max = if (isSuccess) 0.44f else if (isFailed) 0.95f else 0.282f
    )

    val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.anim_loading_success_failed))

    LottieAnimation(
        modifier = modifier,
        composition = composition,
        iterations = if (isSuccess || isFailed) 1 else LottieConstants.IterateForever,
        clipSpec = clipSpecs,
    )
}

As a summary, we have a Lottie animation in Jetpack Compose UI with implemented business logic:

Loading > Success > Reset > Loading > Failure > Reset > …

 

Congratulations! You completed: Lottie Animation in Jetpack Compose and Adding Business Logic on Compose Lottie Animation. 👏

Stay tuned: https://linktr.ee/canerkaseler 🤝

Thanks! ☕️

This article was previously published on proandroiddev.com

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
It’s one of the common UX across apps to provide swipe to dismiss so…
READ MORE
blog
In this part of our series on introducing Jetpack Compose into an existing project,…
READ MORE
blog
In the world of Jetpack Compose, where designing reusable and customizable UI components is…
READ MORE
blog

How to animate BottomSheet content using Jetpack Compose

Early this year I started a new pet project for listening to random radio…
READ MORE

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu