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.



As new libraries start to emerge, it seems that they tend to make our lives as Android developers easier.GSON is one of those libraries, it's main functionality is that it can be used to serialize Java Objects into JSON string representation and vice versa, for deserializing JSON strings into Java Objects.


This example is divided into four steps:

  1. Adding the library to Android
  2. JSON String to POJO class
  3. Converting the JSON String to Java Object and vice versa
  4. Complete code


We’ll start of with a simple tutorial on how to integrate and use the GSON Library in Android.

STEP 1 Adding the library to Android
Open the build.gradle file which is in the app Module and add the following line in side dependencies block:

dependencies {
  …
  compile 'com.google.code.gson:gson:2.5'
}

STEP 2  JSON String to POJO class
Let's say for example we have the following JSON String:

{
"users":[
{ "id":"1", "phone":"111222333", "image":"2014-12-13-08-08-29.jpg", "name":"john", "surname":"doe" }, { "id":"2", "phone":"111222444", "image":"2014-12-13-08-09-29.jpg", "name":"anon", "surname":"nona" }, { "id":"3", "phone":"111222555", "image":"2014-12-13-08-10-29.jpg", "name":"filan", "surname":"fisteku" } ] }
Which is a JSON array, now first we need to parse/serialize the JSON to java objects with the classes that represent the data. So open this website which creates the classes for us, you can copy and paste the JSON into the websites editor, on the right side select Source type: JSON and Annotation style: GSON.At the bottom of the page click the preview button, this will generate the classes which we can create in Java and replace it with the code in the preview


Now first create an Example class and a User class in your android project then replace them with the code in the Preview from the website. They should look like the code below: NOTE delete these two lines:

import javax.annotation.Generated;
@Generated("org.jsonschema2pojo")

First the Example class:
package testgson.gsontest;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

  @SerializedName("users")
  @Expose
  private List<User> users = new ArrayList<User>();

  /**
   *
   * @return
   * The users
   */
  public List<User> getUsers() {
      return users;
  }

  /**
   *
   * @param users
   * The users
   */
  public void setUsers(List<User> users) {
      this.users = users;
  }

}
Second the User class:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class User {

  @SerializedName("id")
  @Expose
  private String id;
  @SerializedName("phone")
  @Expose
  private String phone;
  @SerializedName("image")
  @Expose
  private String image;
  @SerializedName("name")
  @Expose
  private String name;
  @SerializedName("surname")
  @Expose
  private String surname;

  /**
   *
   * @return
   * The id
   */
  public String getId() {
      return id;
  }

  /**
   *
   * @param id
   * The id
   */
  public void setId(String id) {
      this.id = id;
  }

  /**
   *
   * @return
   * The phone
   */
  public String getPhone() {
      return phone;
  }

  /**
   *
   * @param phone
   * The phone
   */
  public void setPhone(String phone) {
      this.phone = phone;
  }

  /**
   *
   * @return
   * The image
   */
  public String getImage() {
      return image;
  }

  /**
   *
   * @param image
   * The image
   */
  public void setImage(String image) {
      this.image = image;
  }

  /**
   *
   * @return
   * The name
   */
  public String getName() {
      return name;
  }

  /**
   *
   * @param name
   * The name
   */
  public void setName(String name) {
      this.name = name;
  }

  /**
   *
   * @return
   * The surname
   */
  public String getSurname() {
      return surname;
  }

  /**
   *

   * @param surname
   * The surname
   */
  public void setSurname(String surname) {
      this.surname = surname;
  }
}

STEP 3 Converting the JSON String to Java Object and vice versa
Finally to actually convert/serialize your JSON to a java object use the code below:

Example example = new Gson().fromJson(json,Example.class);

And to convert your object to a JSON string use the code below:

String json = new Gson().toJson(example);

Complete code:

MainActivity.java

import android.app.Activity;
import android.os.Bundle;

import com.google.gson.Gson;

public class MainActivity extends Activity {

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

      String json = "{\n" +
              "   \"users\":[  \n" +
              "   {  \n" +
              "      \"id\":\"1\",\n" +
              "      \"phone\":\"111222333\",\n" +
              "      \"image\":\"2014-12-13-08-08-29.jpg\",\n" +
              "      \"name\":\"john\",\n" +
              "      \"surname\": \"doe\"\n" +
              "   },\n" +
              "   {  \n" +
              "      \"id\":\"2\",\n" +
              "      \"phone\":\"111222444\",\n" +
              "      \"image\":\"2014-12-13-08-09-29.jpg\",\n" +
              "      \"name\":\"anon\",\n" +
              "      \"surname\": \"nona\"\n" +
              "   },\n" +
              "   {  \n" +
              "      \n" +
              "      \"id\":\"3\",\n" +
              "      \"phone\":\"111222555\",\n" +
              "      \"image\":\"2014-12-13-08-10-29.jpg\",\n" +
              "      \"name\":\"filan\",\n" +
              "      \"surname\": \"fisteku\"\n" +
              "   }\n" +
              "]\n" +
              "}";

      Example example = new Gson().fromJson(json,Example.class);
System.out.println(example.getUsers().get(0).getName());

  }
}

Example.java class

import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

  @SerializedName("users")
  @Expose
  private List<User> users = new ArrayList<User>();

  /**
   *
   * @return
   * The users
   */
  public List<User> getUsers() {
      return users;
  }

  /**
   *
   * @param users
   * The users
   */
  public void setUsers(List<User> users) {
      this.users = users;
  }

}

User.java class

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class User {

  @SerializedName("id")
  @Expose
  private String id;
  @SerializedName("phone")
  @Expose
  private String phone;
  @SerializedName("image")
  @Expose
  private String image;
  @SerializedName("name")
  @Expose
  private String name;
  @SerializedName("surname")
  @Expose
  private String surname;

  /**
   *
   * @return
   * The id
   */
  public String getId() {
      return id;
  }

  /**
   *
   * @param id
   * The id
   */
  public void setId(String id) {
      this.id = id;
  }

  /**
   *
   * @return
   * The phone
   */
  public String getPhone() {
      return phone;
  }

  /**
   *
   * @param phone
   * The phone
   */
  public void setPhone(String phone) {
      this.phone = phone;
  }

  /**
   *
   * @return
   * The image
   */
  public String getImage() {
      return image;
  }

  /**
   *
   * @param image
   * The image
   */
  public void setImage(String image) {
      this.image = image;
  }

  /**
   *
   * @return
   * The name
   */
  public String getName() {
      return name;
  }

  /**
   *
   * @param name
   * The name
   */
  public void setName(String name) {
      this.name = name;
  }

  /**
   *
   * @return
   * The surname
   */
  public String getSurname() {
      return surname;
  }

  /**
   *
   * @param surname
   * The surname
   */
  public void setSurname(String surname) {
      this.surname = surname;
  }

}