Animationdrawable is a simple form of Android animation, which can be used to implement frame animation.
1. Define the friend. xml file under Res/drawable:
<?xml version="1.0" encoding="utf-8"?><animation-list android:oneshot="false"xmlns:android="http://schemas.android.com/apk/res/android"><item android:duration="400" android:drawable="@drawable/friend_light" /><item android:duration="400" android:drawable="@drawable/friend" /></animation-list>
Each item is a frame, Android: Duration = "400" indicates that each frame lasts for 400 ms, and Android: drawable indicates the image to be displayed for each frame.
2. load and execute animations in Java code:
① Loading an animation
Button friend = (Button)findViewById(R.id.friend_btn);friend.setBackgroundResource(R.drawable.friend_anim);AnimationDrawable friend_anim= (AnimationDrawable) friend.getBackground();
② Execute the animation
friend_anim.start();
③ Stop the animation
friend_anim.stop();
3. Note:
By default, animation is executed in oncreate. start (); is invalid, because in oncreate (), animationdrawable is not completely bound to imageview. To start the animation in oncreate (), you can only see the first image.
Solution:
① Call getviewtreeobserver (). addonpredrawlistener () of View ()
friend.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener(){@Overridepublic boolean onPreDraw() {// TODO Auto-generated method stubfriend_anim.start();return true;}});
② Use Handler
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); friend = (Button)findViewById(R.id.friend_btn); handler.postDelayed(new Runnable() { public void run() { friend.setBackgroundResource(R.drawable.friend_anim); friend_anim = (AnimationDrawable) friend.getBackground(); friend_anim.start(); } }, 50);}