Drawable Animation(Frame Animation):帧动画,就像GIF图片,通过一系列Drawable依次显示来模拟动画的效果。
首先,在res/drawable中定义动画
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="true" ><itemandroid:drawable="@drawable/icon"android:duration="200"/><itemandroid:drawable="@drawable/ic_launcher"android:duration="200"/></animation-list>必须以<animation-list>为根元素,以<item>表示要轮换显示的图片oneshot代表着是否只展示一遍,设置为false会不停的循环播放动画duration属性表示各项显示的时间
然后,在布局中将动画设置为背景
注意:动画是指背景动画,所以只能设置background为动画,或在代码中setBackgroundResource(R.drawable.girl),不能设置src为动画。当然两者可以同时设置,这就相当于主角src不变,背景是个动画一直在变。
<ImageView
android:id="@+id/iv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:gravity="center"android:background="@drawable/girl" />
最后,在代码中开启动画
注意:开启或关闭前最好先判断是否为空,应为anim是强转过来的,可能不存在!
SDK中提醒:不要在onCreate中调用start,因为AnimationDrawable还没有完全跟Window相关联,如果想要界面显示时就开始动画的话,可以在onWindowFoucsChanged()中调用start()。
anim = (AnimationDrawable) iv.getBackground();
if (anim != null) anim.stop();if (anim != null) anim.start();