Friday, May 4, 2012

Create frame animation with AnimationDrawable


Create frame animation with AnimationDrawable






Before we start coding for our frame animation, we have to prepare some .png graph for our frames,named android_1.png ~ android_7.png. Copy all graphs to /res/drawable folder.























Create a file /res/anim/anim_android.xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false"
>
<item
android:drawable="@drawable/android_1"
android:duration="100"/>
<item
android:drawable="@drawable/android_2"
android:duration="100"/>
<item
android:drawable="@drawable/android_3"
android:duration="100"/>
<item
android:drawable="@drawable/android_4"
android:duration="100"/>
<item
android:drawable="@drawable/android_5"
android:duration="100"/>
<item
android:drawable="@drawable/android_6"
android:duration="100"/>
<item
android:drawable="@drawable/android_7"
android:duration="100"/>
</animation-list>


Modify main.xml, add a ImageView with android:src="@anim/anim_android".
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<ImageView
android:id="@+id/myanimation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@anim/anim_android"
/>

</LinearLayout>


Modify our activity:
package com.exercise.AndroidAnimation;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;

public class AndroidAnimationActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ImageView myAnimation = (ImageView)findViewById(R.id.myanimation);
final AnimationDrawable myAnimationDrawable
= (AnimationDrawable)myAnimation.getDrawable();

myAnimation.post(
new Runnable(){

  @Override
  public void run() {
   myAnimationDrawable.start();
  }
});
}
}

No comments: