Thursday, July 7, 2011

Android - Animations

Page Transitions

To override the current page transitions when switching activities you can use the overridePendingTransition method. The code snippet shows an example of using the pre-defined Android animations fade_in and fade_out. We need to provide resource ids to the overridePendingTransition method representing the incoming activity and outgoing activity animations.

 Intent i = new Intent(this, ListViewExampleActivity.class);  
 overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);  

View Animations

In this example we will make our own custom animation. The easiest way to create your own animation xml file in Eclipse follows:

1) Right click your project in the Package Explorer
2) New -> Android XML File
3) Select "Animation" as your type, this will place your xml into "res/anim"

The following code shows an example of a scale animation. This animation is using the bounce interpolator. This is much like easing functions in Silverlight. This causes the animation to have a bounce effect. The animation defines the from and to scales, starting at 0 and ending at 1. It also moves the X and Y pivots to 50% so that as the element scales up it scales from the center of the object. Finally the duration is set to 500 milliseconds.

 <?xml version="1.0" encoding="utf-8"?>  
 <set xmlns:android=""  
       android:fromXScale="0.0" android:toXScale="1.0"   
       android:fromYScale="0.0" android:toYScale="1.0"  
       android:pivotX="50%" android:pivotY="50%"  

To apply this animation use the following code:

 Button animBttn = (Button)findViewById(;  
 Animation bttnAnim = AnimationUtils.loadAnimation(mContext, R.anim.button_animation);  

If you would like to trigger the animation we can use the startAnimation method.


List View Animations

This time we will use a translate animation.

 <?xml version="1.0" encoding="utf-8"?>  
 <set xmlns:android=""  
       android:interpolator="@android:anim/overshoot_interpolator" >  

In order to apply this animation to individual list view items we must also create a layoutAnimation xml file.

 <?xml version="1.0" encoding="utf-8"?>  
 <layoutAnimation xmlns:android=""   

To attach the animation to the ListView we will use the setLayoutAnimation method.

 ListView lv = (ListView)findViewById(;  
 lv.setAdapter(new ArrayAdapter<String>(this, R.layout.listitem, PLANETS));  
 //We need to load a LayoutAnimation instead of just an Animation   
 //to set the animation for each individual list item  
 LayoutAnimationController controller = AnimationUtils.loadLayoutAnimation(mContext,R.anim.list_layoutcontroller);  
 //This is the delay between each animation as a fraction of the animation duration  
 //Be sure to set the LayoutAnimation, using setAnimation will set the animation for the entire listview