In this example, there is an ImageView with it's "src" value set to an image. The ImageView's background is set with you own AnimationDrawable, basically an xml in your res/drawable folder. In the activity, the ImageView has a click listener, which creates an AnimationDrawable from the ImageView's background, and just calls the start method of the AnimationDrawable class.
Here is a sample AnimationDrawable described through XML.
<?xml version="1.0" encoding="utf-8"?>And here is the code that gets your animation started.
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@drawable/black" android:duration="200" />
<item android:drawable="@drawable/cyan" android:duration="200" />
<item android:drawable="@drawable/green" android:duration="200" />
<item android:drawable="@drawable/magenta" android:duration="200" />
<item android:drawable="@drawable/navy" android:duration="200" />
<item android:drawable="@drawable/orange" android:duration="200" />
<item android:drawable="@drawable/pink" android:duration="200" />
<item android:drawable="@drawable/white" android:duration="200" />
<item android:drawable="@drawable/yellow" android:duration="200" />
</animation-list>
imageView = (ImageView) findViewById(R.id.ImageButton01);One point to notice is that, you have to remove the ImageView's "src" value, so that the animation is visible, since the animation works by changing the background of the ImageView, else, your animation would be blocked by the ImageView's "src" image.
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AnimationDrawable animator = (AnimationDrawable) imageView.getBackground();
imageView.setImageDrawable(null);
animator.start();
}
});
Once you are done, you can stop the animation, and reset the ImageView's "src" to it's original image.
// Call this method to stop the animationYou can find the whole source code for this example here.
public void stopAnimation(){
AnimationDrawable animator = (AnimationDrawable) imageView.getBackground();
animator.stop();
imageView.setImageResource(R.drawable.icon);
}