The Wayback Machine - https://web.archive.org/web/20241001003731/https://www.geeksforgeeks.org/android-animations-using-java/
Open In App

Android Animations using Java

Last Updated : 23 Feb, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The animation is a method in which a collection of images is combined in a specific way and processed then they appear as moving images. Building animations make on-screen objects seems to be alive. Android has quite a few tools to help you create animations with relative ease. So in this article, let’s learn to create android animations using Java. 

Table of Attributes

XML ATTRIBUTES DESCRIPTION
android:id Sets unique id of the view
android:duration Used to specify the duration of the animation
android:fromDegrees Starting angular position (in degrees)
android:toDegrees Ending angular position (in degrees)
android:fromXScale Starting X size offset
android:toXScale Ending of X size offset
android:fromYScale Starting Y size offset
android:toYScale Ending of Y size offset
android:fromAlpha Starting alpha value for the animation
(1.0 means fully opaque and 0.0 means fully transparent)
android:toAlpha Ending alpha value
android:fromYDelta Change in Y coordinate to be applied at the beginning of the animation
android:toYDelta Change in Y coordinate to be applied at the end of the animation
android:pivotX Represents the X-axis coordinates to zoom from the starting point
android:pivotY Represents the Y-axis coordinates to zoom from the starting point
android:interpolator It defines the rate of change of an animation
android:startOffset Delay occurs when an animation runs (in ms), once start time is reached

How to add animation in Android using Java

Step 1: Create a New Project

  • Start Android Studio (version > 2.2)
  • Go to File -> New -> New Project.
  • Select Empty Activity and click on next
  • Select minimum SDK as 21
  • Choose the language as Java and click on the finish button.
  • Modify the following XML and java files.

Step 2: Modify activity_main.xml file

In the XML file, we have added an ImageView, TextView, and Button inside the RelativeLayout.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/RL1"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="200dp"
        android:layout_height="150dp"
        android:layout_below="@id/textView0"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"
        android:visibility="visible"
        android:src="@drawable/logo2" />
  
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="4 common animations in android"
        android:layout_below="@id/imageView1"
        android:layout_marginTop="50dp"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:fontFamily="sans-serif"
        android:textSize="50px"/>
  
    <Button
        android:id="@+id/button1"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:text="Blink"
        android:layout_below="@id/textView1"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="40dp"/>
  
    <Button
        android:id="@+id/button2"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:text="Slide"
        android:layout_below="@id/textView1"
        android:layout_alignParentRight="true"
        android:layout_marginRight="50dp"
        android:layout_marginTop="40dp"/>
  
    <Button
        android:id="@+id/button3"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:text="Rotate"
        android:layout_below="@id/button1"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="30dp"/>
  
    <Button
        android:id="@+id/button4"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:text="Zoom"
        android:layout_below="@id/button2"
        android:layout_alignParentRight="true"
        android:layout_marginRight="50dp"
        android:layout_marginTop="30dp"/>
  
</RelativeLayout>


Step 3: Add these XML files to the anim directory

After modifying the layout we will create XML files for animations. So we will first create a folder name anim. In this folder, we will be adding the XML files which will be used to produce the animations. For this to happen, go to app/res right-click and then select Android Resource Directory and name it as anim. 

Some Common Types of Animations in Android are,

  1. Blink – Hides the object for 0.6 to 1 second.
  2. Slide – Move the object either vertically or horizontally to its axis.
  3. Rotate – Rotate the object either clockwise or anti-clockwise.
  4. Zoom – Zoom in or out the object in the X and Y-axis.

blinks.xml




<?xml version="1.0" encoding="utf-8"?>
   <alpha android:fromAlpha="0.0"
      android:toAlpha="1.0"
      android:interpolator="@android:anim/accelerate_interpolator"
      android:duration="700"
      android:repeatMode="reverse"
      android:repeatCount="infinite"/>
</set>


rotate.xml




<?xml version="1.0" encoding="utf-8"?>
  
   <rotate xmlns:android="http://schemas.android.com/apk/res/android"
      android:fromDegrees="0"
      android:toDegrees="360"
      android:pivotX="50%"
      android:pivotY="50%"
      android:duration="2500" >
   </rotate>
     
   <rotate xmlns:android="http://schemas.android.com/apk/res/android"
      android:startOffset="5000"
      android:fromDegrees="360"
      android:toDegrees="0"
      android:pivotX="50%"
      android:pivotY="50%"
      android:duration="2500" >
   </rotate>
     
</set>


slides.xml




<?xml version="1.0" encoding="utf-8"?>
   android:fillAfter="true" >
     
   <scale
      android:duration="500"
      android:fromXScale="1.0"
      android:fromYScale="1.0"
      android:interpolator="@android:anim/linear_interpolator"
      android:toXScale="1.0"
      android:toYScale="0.0" />
</set>


zoom.xml




<?xml version="1.0" encoding="utf-8"?>
  
   <scale xmlns:android="http://schemas.android.com/apk/res/android"
      android:fromXScale="0.5"
      android:toXScale="3.0"
      android:fromYScale="0.5"
      android:toYScale="3.0"
      android:duration="4000"
      android:pivotX="50%"
      android:pivotY="50%" >
   </scale>
     
   <scale xmlns:android="http://schemas.android.com/apk/res/android"
      android:startOffset="5000"
      android:fromXScale="3.0"
      android:toXScale="0.5"
      android:fromYScale="3.0"
      android:toYScale="0.5"
      android:duration="4000"
      android:pivotX="50%"
      android:pivotY="50%" >
   </scale>
     
</set>


Step 4: Modify MainActivity.java

To perform animation in android, we have to call a static function loadAnimation() of the class AnimationUtils. We get the result in an instance of the Animation Object. Syntax to create animation object:

Animation object = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.ANIMATIONFILE);

To apply the above animation to an object(Let say in an image), we have to call the startAnimation() method of the object. Syntax to call the method:

ImageView image = findViewById(R.id.imageID); 

image.startAnimation(object);

Methods of animation class:

Method

Description

startAnimation(object) Starts the animation
setDuration(long duration) Sets the duration of animation
getDuration() Gets the duration of animation
end() Ends the animation
cancel() Cancels the animation

Java




import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
  
public class MainActivity extends AppCompatActivity {
    ImageView logo;
    Button blink, slide, rotate, zoom;
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // GFG logo
        logo = findViewById(R.id.imageView1);
  
        // blink button
        blink = findViewById(R.id.button1);
  
        // slide button
        slide = findViewById(R.id.button2);
  
        // rotate button
        rotate = findViewById(R.id.button3);
  
        // zoom button
        zoom = findViewById(R.id.button4);
  
        // blink button listener
        blink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                // call a static function loadAnimation()
                // of the class AnimationUtils
                Animation object
                    = AnimationUtils
                          .loadAnimation(
                              getApplicationContext(),
  
                              // blink file is in anim folder
                              R.anim.blinks);
                // call the startAnimation method
                logo.startAnimation(object);
            }
        });
        // slide button listener
        slide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                // call a static function loadAnimation()
                // of the class AnimationUtils
                Animation object
                    = AnimationUtils
                          .loadAnimation(
  
                              getApplicationContext(),
  
                              // slide file is in anim folder
                              R.anim.slide);
  
                // call the startAnimation method
                logo.startAnimation(object);
            }
        });
  
        // rotate button listener
        rotate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                // call a static function loadAnimation()
                // of the class AnimationUtils
                Animation object
                    = AnimationUtils
                          .loadAnimation(
                              getApplicationContext(),
  
                              // rotate file is in anim folder
                              R.anim.rotate);
  
                // call the startAnimation method
                logo.startAnimation(object);
            }
        });
  
        // zoom button listener
        zoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                // call a static function loadAnimation()
                // of the class AnimationUtils
                Animation object
                    = AnimationUtils
                          .loadAnimation(
                              getApplicationContext(),
  
                              // zoom file is in anim folder
                              R.anim.zoom);
  
                // call the startAnimation method
                logo.startAnimation(object);
            }
        });
    }
}


Output: Run on Emulator
 



Previous Article
Next Article

Similar Reads

How to Create Gradient Animations Like Instagram using Spark Library in Android?
In this article, we are going to implement Spark Library. Here we going to show an animation that will change the colors of the activity linearly. This feature can be simply used to show an animation and when a user loads an activity Or can also be used to show animation on the Splash Screen. Let's see the implementation of this feature. A sample G
2 min read
Android Animations in Kotlin
Animation is a method in which a collection of images are combined in a specific way and processed then they appear as moving images. Building animations make on-screen objects seem to be alive. Android has quite a few tools to help you create animations with relative ease. so in this article we will learn to create animations using Kotlin. below a
5 min read
How to make Check/Tick and Cross animations in Android
AnimatedVectorDrawable class was introduced in API 21 and is used to animate Vector Drawables beautifully and easily. Using AnimatedVectorDrawable, one can: Rotate, Scale, Translate VectorDrawables Animate the VectorDrawable such as fill color etc. Draw paths and do Path Morphing An AnimatedVectorDrawable element has a VectorDrawable attribute, and
4 min read
How to Apply View Animations Effects in Android?
Android View Animations are used to apply amazing animations on TextView and EditText in the android application. Such animations provide the app with a smooth look in a new way. In this article, we are going to develop the Android View Animation effect in Android Studio. What we are going to build in this article? In this article, we will develop
3 min read
Fluid Slider Animations in Android
Here we are going to see how we can implement Fluid Slider Animation in android studio using Kotlin. The idea to use this slider scale in our applications makes our UI look beautiful and more interactive. What is Fluid Slider Animation? A Fluid Slider is a slider widget with a popup bubble displaying the precise value. Its uses in different applica
3 min read
Android Rotate animations in Kotlin
Rotate animation is a special kind of animation in Android which controls the Rotation of an object. These type of animations are usually used by developers to give a feel to the user about the changes happening in the application like loading content, processing data, etc. By using the rotate animation effect, an object can be rotated in the X-Y p
4 min read
How to Control Lottie Animations Programmatically in Android?
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 insid
3 min read
Java For Android - Building Your First Android App
Android app development can play a major role in writing the app functionalities using Java programming. Every activity can be designed with Java programming. Android apps are developed using the Android Studio IDE, which provides the environment for Java development for Android programming. PrerequisitesJava ProgrammingAndroid Studio in your syste
5 min read
Android Java Projects - Build Your First Android App from Scratch
Are you eager to boost your Android development skills and create cool projects? Our blog post, "Android Java Projects," is here to help! Whether you're just starting your software development career or want to add good projects to your CV then, working on real projects is the best way to learn and grow as a developer. In this post, we've gathered
6 min read
How to Add OpenCV library into Android Application using Android Studio?
OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. When it integrated with various libraries,
3 min read
How to Capture a Screenshot and Screen Recording of an Android Device Using Android Studio?
Android Studio is the official IDE (Integrated Development Environment) for Android app development and it is based on JetBrains’ IntelliJ IDEA software. Android Studio provides many excellent features that enhance productivity when building Android apps. Whenever we are developing an app and in that device, you don't know how to capture screenshot
2 min read
How to Make a Scientific Calculator Android App using Android Studio?
The calculator is the app that is present on every android device. This app comes pre-installed or we can also install another application from Play Store. It is one of the most used applications for college students for making any calculations. In this article, we will take a look at building a simple scientific calculator app in Android using Kot
13 min read
Star Shower in Android using Android Property Animation
In this article, we are going to create a star shower using android property animation. We will create a slightly more involved animation, animating multiple properties on multiple objects. For this effect, a button click will result in the creation of a star with a random size, which will be added to the background container, just out of view of t
7 min read
Android Runtime Permissions with Dexter using Android Jetpack Compose
Android applications require the usage of hardware devices within the android applications such as microphones or cameras. For using these devices within any android application. Permissions for using this hardware have to be provided to the application. For giving these permissions to the application runtime permissions are used. Handling permissi
7 min read
Android Animation using Android Studio
In today's world which is filled with full of imagination and visualizations, there are some areas that are covered with the word animation. When this word will come to anyone’s mind they always create a picture of cartoons and some Disney world shows. As we already know that among kids, animation movies are very popular like Disney world, Doraemon
5 min read
Android Manifest File in Android
Every project in Android includes a Manifest XML file, which is AndroidManifest.xml, located in the root directory of its project hierarchy. The manifest file is an important part of our app because it defines the structure and metadata of our application, its components, and its requirements. This file includes nodes for each of the Activities, Se
5 min read
Android | Android Application File Structure
It is very important to know about the basics of Android Studio's file structure. In this article, some important files/folders, and their significance is explained for the easy understanding of the Android studio work environment. In the below image, several important files are marked: All of the files marked in the above image are explained below
3 min read
What's Android Interface Definition Language (AIDL) in Android?
The Android Interface Definition Language (AIDL) is analogous to other IDLs you would possibly have worked with. It allows you to define the programming interface that both the client and repair agree upon so as to speak with one another using interprocess communication (IPC). Traditionally the Android way a process cannot access the memory of some
7 min read
Android | Running your first Android app
After successfully Setting up an Android project, all of the default files are created with default code in them. Let us look at this default code and files and try to run the default app created. The panel on the left side of the android studio window has all the files that the app includes. Under the java folder, observe the first folder containi
3 min read
How to Clone Android Project from GitHub in Android Studio?
Android Studio provides a platform where one can build apps for Android phones, tablets, Android Wear, Android TV, and Android Auto. Android Studio is the official IDE for Android application development, based on IntelliJ IDEA. One can develop Android Applications using Kotlin or Java as the Backend Language, and it provides XML for developing Fro
3 min read
8 Best Android Libraries That Every Android Developer Should Know
Android is an operating system which is built basically for Mobile phones. It is used for touchscreen mobile devices like smartphones and tablets. But nowadays these are utilized in Android Auto cars, TV, watches, camera, etc. Android has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bought i
5 min read
How to Add Audio Files to Android App in Android Studio?
The audio file format is a file format for saving digital audio data on a computer system and all are aware of audio files. So in this article, we are going to discuss how can we add audio files to the android app. There are three major groups of audio file formats: Format Name Description Examples Uncompressed audio formatsUncompressed audio forma
3 min read
Different Ways to Change Android SDK Path in Android Studio
Android SDK is one of the most useful components which is required to develop Android Applications. Android SDK is also referred to as the Android Software Development Kit which provides so many features which are required in Android which are given below: A sample source code.An Emulator.Debugger.Required set of libraries.Required APIs for Android
5 min read
Different Ways to Fix “Select Android SDK” Error in Android Studio
Android SDK is one of the most useful components which is required to develop Android Applications. Android SDK is also referred to as the Android Software Development Kit which provides so many features which are required in Android which are given below: A sample source code.An Emulator.Debugger.Required set of libraries.Required APIs for Android
5 min read
Different Ways to Analyze APK Size of an Android App in Android Studio
APK size is one of the most important when we are uploading our app to Google Play. APK size must be considered to be as small as possible so users can visit our app and download our app without wasting so much data. In this article, we will take a look at How we can analyze our APK in Android Studio to check the APK size. Android Studio itself pro
3 min read
Different Ways to fix "Error running android: Gradle project sync failed" in Android Studio
Gradle is one of the most important components of Android apps. It handles all the backend tasks and manages all the external dependencies which we will be going to use in building our Android Application. Sometimes due to any issue or after formatting of your pc. Some of the Gradle files may get deleted unexpectedly. So when you will start buildin
3 min read
How to Fix “Failed to install the following Android SDK packages as some licenses have not been accepted” Error in Android Studio?
When you download the latest Android SDK tools version using the command line to install SDKs and you just try to build gradle then this error shows up: Failed to install the following Android SDK packages as some licenses have not been accepted. platforms;android-27 Android SDK Platform 27 build-tools;27.0.3 Android SDK Build-Tools 27.0.3 To build
4 min read
How to fix "Android Studio doesn't see device" in Android Studio?
In Android Studio, sometimes the list of devices and emulators doesn't list your physical device when you try to plug it in. Or you may have faced a situation when you plugged the phone in for the first time, no dialog appeared asking if you trust the computer. But the laptop is already allowed to connect to the mobile device. However, the button R
4 min read
How to Fix "Android studio logcat nothing to show" in Android Studio?
Logcat Window is the place where various messages can be printed when an application runs. Suppose, you are running your application and the program crashes, unfortunately. Then, Logcat Window is going to help you to debug the output by collecting and viewing all the messages that your emulator throws. So, this is a very useful component for the ap
2 min read
How to Build a Number Shapes Android App in Android Studio?
Android is a vast field to learn and explore and to make this learning journey more interesting and productive we should keep trying new problems with new logic. So, today we are going to develop an application in android studio which tells us about Numbers that have shapes. We will be covering two types of numbers i.e. triangular and square. So, f
4 min read
Article Tags :
Practice Tags :