ObjectAnimator in Android with Example

15 Dec, 2021
ObjectAnimator is a Subclass of ValueAnimator, which allows us to set a target object and object property to animate. It is an easy way to change the properties of a view with a specified duration. We can provide the end position and duration of the animation. Let us create a simple version of the Glass Bridge game in android studio using ObjectAnimator.
In this game, the player had to hop across a suspended bridge lined with panels of either regular or tempered glass. If they chose correctly, they would land on tempered glass and be safe. if they chose the wrong side, the glass breaks and the player will fall down. We are going to create a very simple version of the glass bridge game in android using ObjectAnimator. A sample video 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 Java language.
It’s really easy to create a simple Animation using ObjectAnimator. Here are the steps:
Create an instance of the ObjectAnimatorSet the motion behavior parametersSet the Duration of the animationStart the animation
Create an instance of the ObjectAnimator
Set the motion behavior parameters
Set the Duration of the animation
Start the animation
ObjectAnimator API contains methods to create instances of ObjectAnimator depending on the type of attribute we are animating. When changing the position of a view we will use the translationX and translationY attributes.
ObjectAnimator animation = ObjectAnimator.ofFloat(view,"translationY",1300f);
animation.setDuration(4000);
These properties control where the view is located as a delta from its left coordinate, top coordinate, and elevation, which are set by its layout container.
TRANSLATION_X – Left Coordinate
TRANSLATION_Y – Top Coordinate
TRANSLATION_Z – Depth of the view relative to its elevation.
ofFloat() – Constructs and returns an ObjectAnimation that animates coordinates.
setDuration() – Sets the length of the animation.
setupStartValues() – Tells the object to use the appropriate information to extract starting values for the animation
setupEndValues() – Tells the object to use the appropriate information to extract ending values for the animation
Let’s build a simple version of the glass bridge game using ObjectAnimator. We are going to implement this project using the Java Programming language.
Step 1: Create a new project
First, we want to 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. 
Step 2: Add an Image to the drawable folder
To add an image to the drawable folder please refer to How to Add Image to Drawable Folder in Android Studio. You can simply add an image to the drawable folder by just copying and pasting the image in the drawable folder.
Navigation: app > res >drawable
I’m also attaching the two images I used in this project.
Glass Image
Glass Image
Broken Glass Image
Broken Glass Image
Step 3: Working with activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity"    android:background="@color/black">      <!-- Adding the first Glass -->    <ImageView        android:id="@+id/glass1"        android:layout_width="150dp"        android:layout_height="145dp"        android:background="#2A3434"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintHorizontal_bias="0.065"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent"        app:layout_constraintVertical_bias="0.053"        app:srcCompat="@drawable/glass"        app:tint="#9306FFEA" />      <!-- Adding the Second Glass -->    <ImageView        android:id="@+id/glass2"        android:layout_width="150dp"        android:layout_height="145dp"        android:background="#2A3434"        app:layout_constraintBottom_toBottomOf="@+id/glass1"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintHorizontal_bias="0.746"        app:layout_constraintStart_toEndOf="@+id/glass1"        app:layout_constraintTop_toTopOf="@+id/glass1"        app:layout_constraintVertical_bias="0.0"        app:srcCompat="@drawable/glass"        app:tint="#FF007B" />  </androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Add animation to the ImageView using ObjectAnimator.
Java
import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity;  import android.animation.Animator;import android.animation.AnimatorListenerAdapter;import android.animation.ObjectAnimator;import android.os.Build;import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.Toast;  public class MainActivity extends AppCompatActivity {      boolean isSelected;    int side=0;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          // Creating Views for the two images        ImageView Glass1=findViewById(R.id.glass1);        ImageView Glass2=findViewById(R.id.glass2);          // Creating Animations using ObjectAnimators        ObjectAnimator AnimateGlass1 = ObjectAnimator.ofFloat(Glass1,"translationY",1300f);        AnimateGlass1.setDuration(4000);          ObjectAnimator AnimateGlass2 = ObjectAnimator.ofFloat(Glass2,"translationY",1300f);        AnimateGlass2.setDuration(4000);          // Generate a random number to choose a random side        side= (int) (Math.random() * 2);        isSelected=false;           // Adding onClick Listeners to check the correct side        Glass1.setOnClickListener(new View.OnClickListener() {            @RequiresApi(api = Build.VERSION_CODES.KITKAT)            @Override            public void onClick(View v) {                if(side==1)                {                    // Wrong Side                    // Change the image to Broken Glass                    Glass1.setImageResource(R.drawable.broken_glass);                      // Stop the Animation                    AnimateGlass1.pause();                    AnimateGlass2.pause();                    isSelected=false;                    AnimateGlass1.removeAllListeners();                    Toast.makeText(MainActivity.this, "Try Again!", Toast.LENGTH_SHORT).show();                }                else {                    // Correct Side                    // Change isSelected to True                    isSelected=true;                    Toast.makeText(MainActivity.this, "Lucky!", Toast.LENGTH_SHORT).show();                }              }        });          Glass2.setOnClickListener(new View.OnClickListener() {            @RequiresApi(api = Build.VERSION_CODES.KITKAT)            @Override            public void onClick(View v) {                if(side==0)                {                    // Wrong Side                    // Change the image to Broken Glass                    Glass2.setImageResource(R.drawable.broken_glass);                    // Stop the Animation                    AnimateGlass1.pause();                    AnimateGlass2.pause();                    isSelected=false;                    AnimateGlass1.removeAllListeners();                    Toast.makeText(MainActivity.this, "Try Again!", Toast.LENGTH_SHORT).show();                }                else {                    // Correct Side                    // Change isSelected to True                    isSelected=true;                    Toast.makeText(MainActivity.this, "Lucky!", Toast.LENGTH_SHORT).show();                }            }        });          // Adding Animation End Listener        AnimateGlass1.addListener(new AnimatorListenerAdapter() {            @Override            public void onAnimationEnd(Animator animation) {                super.onAnimationEnd(animation);                // Check any of the glasses are selected                if(isSelected)                {                    // Continue the game                    View glass1view=Glass1;                    View glass2view=Glass2;                    // Place the glasses again in the top                    glass1view.setY(0f);                    glass2view.setY(0f);                    // new random side                    side= (int) (Math.random() * 2);                    // start the animations                    AnimateGlass1.start();                    AnimateGlass2.start();                }                else {                    // No glasses are Selected                    Glass1.setImageResource(R.drawable.broken_glass);                    Glass2.setImageResource(R.drawable.broken_glass);                    // Stop the Animation                    AnimateGlass1.cancel();                    AnimateGlass2.cancel();                    Toast.makeText(MainActivity.this, "Try Again!", Toast.LENGTH_SHORT).show();                }            }        });          // Starting the Animations for the First Time        AnimateGlass1.start();        AnimateGlass2.start();    }}
Output:
Here is the output of our project.
sumitgumber28
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
How to Add Views Dynamically and Store Data in Arraylist in Android?
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Stack Widget
How to Communicate Between Fragments in Android?
Activity Lifecycle in Android with Demo App
Introduction to Android Development
Animation in Android with Example