Hi and welcome to another tutorial from CodingDemos :)
In this tutorial, you will learn how to add a professional-looking animation in android with a few lines of code. You will be using a third-party library called Lottie that will allow you to add the animation easily.
Here are the steps:
1- Open up Android Studio.
2- Open Build.Grade Module App and add the library dependency.
implementation "com.airbnb.android:lottie:3.4.1"
3- Click on Sync Now to sync your project files, so that you can use the library.
4- Search for the animation that you want to use and make sure to download the file.
5- Include the downloaded animation file inside your project Raw folder.
6- Open activity_main.xml file and add LottieAnimationView and Button.
com.airbnb.lottie.LottieAnimationView
android:id="@+id/animation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="@+id/controlAnimation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:lottie_autoPlay="false"
app:lottie_loop="true"
app:lottie_rawRes="@raw/pizza"
Button
android:id="@+id/controlAnimation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play Animation"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
7- Open MainActivity.java file, here you will declare the views and reference them based on their IDs.
LottieAnimationView lottieAnimationView = findViewById(R.id.animation);
Button controlAnimation = findViewById(R.id.controlAnimation);
8- Next you need to allow the user to taps on the button to control the animation using OnClickListener.
controlAnimation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
9- Inside the button OnClick method, you need to check the status of the animation whether the animation is playing or not. You will then change the label on the button based on it.
if (lottieAnimationView.isAnimating()) {
controlAnimation.setText("Play Animation");
lottieAnimationView.cancelAnimation();
} else {
controlAnimation.setText("Stop Animation");
lottieAnimationView.playAnimation();
}
10- Now build and run the app to see the result :)
#androiddevelopment #androidprogramming #androidtutorial #androidstudio #androidstudiotutorial #java #codingdemos
Links:
Android Lottie documentation: http://airbnb.io/lottie/#/android
Lottie Animation library: https://lottiefiles.com/
Website: https://www.codingdemos.com
FaceBook: / codingdemos
Introduction 00:00
Final output 00:15
Animation ideas 01:10
Add Lottie dependency library 03:20
Add Lottie animation JSON file 04:30
Add Lottie view in XML file 05:40
Add Button view in XML file 08:35
Add Lottie & Button in Java file 10:10
Start/stop Lottie animation 10:55
Conclusion 13:50