Android Animations Explained Programmatically and Through XML

by 3:50 AM 2 comments
From this post you will take away the knowledge on animations such as:
  • Translate animations(moving a view)
  • Alpha animations (making a view more or less transparent)
  • Scale animations (changing a views size)
  • Rotate animations (rotating the view)
  • Multiple animations at once
  • Interactive animations (interacting with the view which animates)

Animations always make an app stand out, give it a feel on where and how things are going, basically animations give apps a sense of life.

We'll start of with a simple animation which moves a view from point A to point B. So create a new android application project and replace the following code to your activity_main.xml:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"                         xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/our_map"
    android:layout_width="match_parent"
    android:padding="10dp"
    android:layout_height="match_parent">
   <View 
        android:id="@+id/view"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="@drawable/background"
   />
 </RelativeLayout>



Here Create a new file in the drawable folder called background.xml and add the following code to it background.xml

<?
xml version="1.0" encoding="utf-8"?>


<?
xml version="1.0" encoding="utf-8"?>

    <shape xmlns:android="http://schemas.android.com/apk/res/android"                android:shape="oval">
        <size android:width="50dp"

           android:height="50dp"/>
       <solid android:color="#ff5000"/>
    </shape>
 



Here we are adding a RelativeLayout and one single child which is a View and has a red circular background. Now open your MainAcitivity.java and add the following code: 

MainAcitivity.java 
import android.app.Activity;
import android.os.Bundle;
import android.view.View; 

import android.widget.RelativeLayout; 
public class MainActivity extends Activity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final RelativeLayout view_map = (RelativeLayout) findViewById(R.id.our_map);
        final View view = findViewById(R.id.our_map);

        //... replace the up coming code here    }
}

As I said we can add different kind of animations to our view and there are different ways to animate our views through xml and programmatically. Below you have the animation examples in xml and java code xml animations are actually called tween animations but can be defined in xml, to create a tween animation from xml you have to follow these steps:

  1. Create the anim folder
  2. Create a xml file in the anim folder which holds a set or one animation
  3. Add attributes to the animation such as duration, toXDelta, fromXDelta etc
  4. Load the animation from resources with the following line of code:Animation animation = AnimationUtils.loadAnimation(context,R.anim.animation)
  5. Set the animation to a view by:view.setAnimation(animation);


Translate Animation

XML

Create a new folder in the res folder called anim - res/anim/ in this folder you can add all of your xml based animations. Now create a new file in the anim folder called translate.xml animation and copy and paste the code below into it:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:fillEnabled="true">

    <translate
        android:duration="3000"
        android:fromXDelta="0"
        android:fromYDelta="0"
        android:toXDelta="500"
        android:toYDelta="500" />
</set> 



Replace the comment in the MainActivity.java class with the following code: 

//... replace the up coming code here 

With: 
Animation animation = AnimationUtils.loadAnimation(this,R.anim.translate); view.setAnimation(animation); 


With Now run your code and you'll see the red circle move towards the center of your screen.

JAVA

Replace the comment in the MainActivity.java class with the following code: 
//... replace the up coming code here 
With: 

view.animate().translationX(500).setDuration(3000).start(); view.animate().translationY(500).setDuration(3000).start();

Alpha Animation

The alpha animation has a fromAlpha and toAlpha properties which are float values starting from 0.0 as fully transparent and 1.0 as fully opaque(not transparent)

XML Fade Out

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:fillEnabled="true">

    <alpha
        android:duration="3000"
        android:fromAlpha="1.0"
        android:toAlpha="0.0" />
</set>

JAVA Fade Out


view.animate().alpha(0).setDuration(3000).start();

XML Fade In



<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:fillAfter="true"
    android:fillEnabled="true">

    <alpha
        android:duration="3000"
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
</set>

JAVA Fade In

view.animate().alpha(1).setDuration(3000).start();

Scale Animation

The scale animation has a pivotX and pivotY properties  which are float or percentage values that attribute the points from where will the views expansion start, in our example we will grow the view from its center, so our view will expand normally, but we can make it expand from one side more than an other side by changing those two properties. the toXScale and toYScale properties multiply the current width, height of the view to the specified values.

XML



<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:fillEnabled="true">

    <scale
        android:duration="3000"
        android:fromXScale="1"
        android:fromYScale="1"
        android:pivotX="0%"
        android:pivotY="0%"
        android:toXScale="3"
        android:toYScale="3" />
</set> 

JAVA

view.animate().scaleX(3).setDuration(3000).start(); view.animate().scaleY(3).setDuration(3000).start();

Rotate Animation

The scale animation has a pivotX and pivotY properties  which are float or percentage values that attribute the points from where will the views center rotation point is. It's hard to notice a circle rotating when its filled with one color so lets just go into our res/drawable/background.xml file this line of code: 

android:shape="oval" 
to: 
android:shape="rectangle"

XML



<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:fillEnabled="true">

    <rotate
        android:duration="3000"
        android:fromDegrees="0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="250" />
</set> 

JAVA

view.animate().scaleX(3).setDuration(3000).start(); view.animate().scaleY(3).setDuration(3000).start();

Multiple animations simultaneously

Now we'll animate the view as if it were to be rotating and moving to the center of the screen will disappearing and shrinking all at the same time. Here we introduce a new animation property called startOffset which we'll use to start each animation in a sequence (one after another). Use the rectangle code for the views background:

XML


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:fillEnabled="true">

    <translate
        android:duration="4000"
        android:fromXDelta="0"
        android:fromYDelta="0"
        android:startOffset="1"
        android:toXDelta="500"
        android:toYDelta="500" />

    <alpha
        android:duration="3000"
        android:fromAlpha="1.0"
        android:startOffset="1000"
        android:toAlpha="0.0" />

    <rotate
        android:duration="1000" 
        android:fromDegrees="0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:startOffset="3000"
        android:toDegrees="90" />

    <scale
        android:duration="4000"
        android:fromXScale="1"
        android:fromYScale="1"
        android:pivotX="0%"
        android:pivotY="0%"
        android:startOffset="1"
        android:toXScale="0.5"
        android:toYScale="0.5" />
</set>

Interactive animations

What we mean by Interactive animations is that when the user interacts, touches, presses the screen our views will respond to those interactions. These are very important as we use apps daily we see lots of different animations will swiping up and down to see more posts, flinging views of the screen for deletion, flashing views to get the users attention, holding a view to select or multi select other views, there are a lot of appliances to interactions between users and our apps. Here we will be showing an example on how to move a view to the position where the user touches the screen.
This should be your activity_main.xml code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/our_map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <View
        android:id="@+id/view"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="@drawable/background" />
</RelativeLayout> 
We'll use the res/drawable/background.xml from the examples above, use either round or rectangle shapes which ever you like more. Now we'll add a TouchListener to our_map RelativeLayout 

MainActivity.java 

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class MainActivity extends Activity {
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final View view = findViewById(R.id.view);
        final View view_map = findViewById(R.id.our_map);
        view_map.setOnTouchListener(new View.OnTouchListener() {
            @Override            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
    }
} 
Here we have registered the view_map to listen for touch events. Now we can implement the code that moves the view to the position where the user touched the screen. The event parameter on the onTouch method has two properties X and Y which are the positions of the users touch, we'll use these two coordinates to move the view. 

MainAcitivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.BounceInterpolator;

public class MainActivity extends Activity {
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final View view = findViewById(R.id.view);
        final View view_map = findViewById(R.id.our_map);
        view_map.setOnTouchListener(new View.OnTouchListener() {
            @Override            public boolean onTouch(View v, MotionEvent event) {
                float x = event.getX();
                float y = event.getY();
                view.animate().translationX(x).setDuration(3000).start();
                view.animate().translationY(y).setDuration(3000).start();
                return false;
            }
        });
    }
}
Now run your app and start touching the screen you'll see your view chasing your finger.



Unknown

Android Developer at Appsix LLC

I love stickers and reading books. A cool website that I've found was commitstrip.com
Currently reading: The pragmatic programmer, and The C programming language.
Currently working: an android app, and on a web project with laravel.
Im a 9gag enthusiast.
I write code at work and at home for fun or out of pure boredom.
Programming Languages that I've worked with: Java PHP C# PLSQL JavaScript
Thanks for reading.



2 comments :

  1. Please let me know if you’re looking for an author for your site. You have some great posts, and I think I would be a good asset. If you ever want to take some of the load off, I’d like to write some material for your blog in exchange for a link back to mine. Please shoot me an email if interested. Thanks.

    Surya Informatics

    ReplyDelete
  2. Please let me know if you’re looking for an author for your site. You have some great posts, and I think I would be a good asset. If you ever want to take some of the load off, I’d like to write some material for your blog in exchange for a link back to mine. Please shoot me an email if interested. Thanks.
    Surya Informatics

    ReplyDelete