How to implement Frame by Frame Animation in Android?

by / Wednesday, 18 December 2013 / Published in Android

Animation is the state of being alive. Something that gives  an illusion.Frame by Frame animation is an animation defined in XML that shows a sequence of images in order. In Frame Animation, frames  are swapped repeatedly, so that it appears continuous to the human eye and we feel that it is animated. Frame is referred to an image.

In this example we will go through, how to use Frame by Frame Animation.

Code for layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#E6E6E6"
android:gravity="center">
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/imageAnimation"
android:adjustViewBounds="true"
android:layout_gravity="center"/>
</LinearLayout>

Code for Activity:

public class Animation extends Activity {

/**
* Reference to the ImageView which will display the animation.
*/
ImageView animation;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
animation = (ImageView)findViewById(R.id.imageAnimation);

animation.setBackgroundResource(R.drawable.animation);// the frame-by-frame animation defined as a xml file within the drawable folder

/*
* NOTE: It's not possible to start the animation during the onCreate.
*/
}

@Override
/**
* This method is called whenever the Activity becomes visible or invisible to the user.
* During this method call its possible to start the animation.
*/
public void onWindowFocusChanged (boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
AnimationDrawable frameAnimation =
(AnimationDrawable) animation.getBackground();
if(hasFocus) {
frameAnimation.start();
} else {
frameAnimation.stop();
}
}
}

code for res/drawable/animation.xml:

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">

<item android:drawable="@drawable/bubble1" android:duration="100" />
<item android:drawable="@drawable/bubble2" android:duration="100" />
<item android:drawable="@drawable/bubble3" android:duration="100" />
<item android:drawable="@drawable/bubble4" android:duration="100" />
<item android:drawable="@drawable/bubble5" android:duration="100" />

</animation-list>

TOP