本章内容
在之前动画概述中,已经详细说了Drawable Animation,本章直接上效果。
效果图:
代码中,我使用了两种方式来实现这种动画,先看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/a"
android:duration="150" />
<item
android:drawable="@drawable/b"
android:duration="150" />
<item
android:drawable="@drawable/c"
android:duration="150" />
<item
android:drawable="@drawable/d"
android:duration="150" />
<item
android:drawable="@drawable/e"
android:duration="150" />
<item
android:drawable="@drawable/f"
android:duration="150" />
<item
android:drawable="@drawable/g"
android:duration="150" />
<item
android:drawable="@drawable/h"
android:duration="150" />
<item
android:drawable="@drawable/i"
android:duration="150" />
</animation-list>
XML文件由作为根节点元素,在根节点里面,是一系列的的子节点,在子节点里面定义了要展示的图片和每一帧持续的时间,并且可以看到效果中,没有停止,这里在xml中我设置了 android:oneshot=”false”,这样就可以无限循环动画了,如果设置为 true,那么就只会进行一次动画,并停在最后一帧。
在ACTIVITY中的代码也很简单:
image.setBackgroundResource(R.drawable.drawable_list);
drawable_animtaiton1 = (AnimationDrawable) image.getBackground();
....
drawable_animtaiton1.start();
第二种就是在代码动态添加图片和显示时间
drawable_animtaiton2 = new AnimationDrawable();
drawable_animtaiton2.addFrame(new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.a)), DURATION2);
drawable_animtaiton2.addFrame(new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.b)), DURATION2);
drawable_animtaiton2.addFrame(new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.c)), DURATION2);
drawable_animtaiton2.addFrame(new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.d)), DURATION2);
drawable_animtaiton2.addFrame(new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.e)), DURATION2);
drawable_animtaiton2.addFrame(new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.f)), DURATION2);
drawable_animtaiton2.addFrame(new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.g)), DURATION2);
drawable_animtaiton2.addFrame(new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.h)), DURATION2);
drawable_animtaiton2.addFrame(new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.i)), DURATION2);
image2.setBackground((AnimationDrawable)drawable_animtaiton2);
.....
drawable_animtaiton2.start();
需要注意的是:AnimationDrawable的start()方法不能够在Activity的onCreate()调用,因为这个时候,AnimationDrawable可能还没有完全的绑定到Window上。如果我们想马上播放动画,我们可以在 onWindowFocusChanged()方法里面调用,因为这个方法是在window已经获取到焦点之后回调的,可以保证已经绑定结束。