Monday, April 13, 2009

Android frame by frame animations

Frame by frame animations are traditional animations in the sense that they are created with a sequence of different images, played in order, like a roll of film. The AnimationDrawable class is the basis for frame animations.

This is a sample video of the Android Earth Animation application:

The animations is presented as a Button background and every time you touch it the animation stops and next time the rotational direction is changed (prograde and retrograde motion).

Usually, these animations are defined in XML resource files in the res/anim folder, using the tag and including the drawables composing th e animation.

Some information can be found at Android developers: Frame Animation, however if you want to automatically start the animation when the Activity is just started you'll find a hard time.
You may think that you can start the animation in onCreate or onResume, but it's not going to work.
The simplest solution is to delay the animation start using a timer in onResume:

/* (non-Javadoc) * @see */ @Override protected void onResume() { super.onResume(); (new Timer(false)).schedule(new AnimationTimer(earthButtonAnimation), 100); }

Where AnimationTimer is defined as

private static class AnimationTimer extends TimerTask { AnimationDrawable animation; public AnimationTimer(AnimationDrawable animation) { this.animation = animation; } @Override public void run() { animation.start(); this.cancel(); } }

As usual you can install or download the application or its source code from
Hope this helps and save you some time.


Latest code, including some of the contributions, can be found at github.
Fell free to send me patches and corrections.
Post a Comment