Tuesday 5 November 2013

Switching Android Activities : Fade Out - Fade In Animation

In this post, I will show you how to implement a basic slide-out-slide-in transition animation when switching between Activities in an Android application.

Animation in Android can be implemented either in Java code or XML markup. In this post we will use the latter approach. A similar post will be published on implementing animations in Java code.

We are going to make some assumptions. We will assume that we have 2 activity classes, ActivityA and ActivityB. Now when a button is clicked on ActivityA, we want it to slide out and ActivityB will slide in.

To define the animations in xml, create a file call fade_in.xml in the anim directory found in the res folder and paste the following code.

NOTE : The filename could be any valid android resource name

CODE FOR slide_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="-100%p" android:toXDelta="0" android:duration="500" />
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="100" android:startOffset="200" />

</set>

Create another file called fade_out.xml in the anim directory found in the res folder of your project and paste in the following code. Again, the name of this file could be any valid android resource name.

CODE FOR slide_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="-100%p" android:duration="500" />
    <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="100" android:startOffset="200" />

</set>

EXPLANATION :
<translate android:fromXDelta="-100%p" android:toXDelta="0" android:duration="500" />

The above code means the X position of the sliding Activity should change from -100 to 0 in 500 milliseconds.

<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="100" android:startOffset="200" />
The above code changes the transparency of the sliding Activity from 1 to 0.

To show ActivityB following an event in ActivityA and apply the defined animations use the following code

startActivity(new Intent(ActivityA.this,ActivityB.class));
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);

If you don't understand anything just write it in a comment and get it answered.

No comments:

Post a Comment