Lottie is a mobile library for Android and iOS that parses Adobe After Effects animations exported as JSON with Bodymovin and renders them natively on mobile. The Lottie animations are free to use vector animation files. Many famous applications use this such as Uber, Netflix, Google, Airbnb, Shopify, etc. Using Lottie, one can put animations inside a mobile (Android/iOS) application and even control them. Through this article, we would like to share with you the implementation of a method to control a JSON animation in Android using Lottie. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
Note: To use Lottie Animation in Android please refer to How to add Lottie Animation in an Android app
Steps to Control Lottie Animations
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add library to the build.gradle file
For implementing an animation using Lottie, first, implement a dependency implementation ‘com.airbnb.android:lottie:$lottieVersion’ into the build.gradle file of the app. The latest version in October 2020 is 3.4.2, replace $lottieVersion with this value. Now sync the project by clicking the sync option which appears after every change made to the build.gradle file. Remember, build.gradle is always a Groovy or a Kotlin file.
Step 3: Add a lottie animation file to the project
Choose any animation from here and download the JSON file of animation.
Now go to app > res > right-click > New > Folder > Raw Resource Folder and copy the JSON file to this raw folder.
Step 4: Working with the activity_main.xml file
In the activity_main.xml file declare a Lottie object by specifying the parameters. Also declare two Buttons, one to start the animation and one to pause it. The primary parameters are:
- lottie_rawRes: takes in the JSON animation to be displayed.
- lottie_loop: boolean value, that decides if the animation is on loop or not depending upon the boolean value supplied.
- lottie_autoPlay: boolean value, which decides if the animation plays as soon as it is initialized.
It is important to note that the JSON animation should only be kept in a folder named raw under the res folder since the functions are made explicitly to call this file path. And the name of the JSON file should not contain any special character other then ‘_‘.
Step 5: Working with the MainActivity.kt file
Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.