Animation Drawable可以让你把一系列的图片像幻灯片一样一张一张地显示在屏幕上。Drawable Animation的基类是AnimationDrawable.
非常值得注意的一点是,虽然Animation Drawable的效果看起来像动画一样,但在实际的代码处理中应该将其视为Drawable,而事实上它继承于Drawable,其XML配置文件也是放置在res/drawable目录下。
Animation Drawable在XML配置中使用<animation-list>作为根元素,然后使用<item>元素来定义每个帧显示drawable资源和该drawable资源的显示持续时间。下面是一个示例:
- <animation-list xmlns:android="http://schemas.android.com/apk/res/android"
- android:oneshot="true">
- <item android:drawable="@drawable/rocket_thrust1" android:duration="200" />
- <item android:drawable="@drawable/rocket_thrust2" android:duration="200" />
- <item android:drawable="@drawable/rocket_thrust3" android:duration="200" />
- </animation-list>
上面的XML配置中只包含了三个帧的内容,每个帧都会延时200ms。如果android:oneshot属性设置为 true ,那么该Animation Drawable只会运行一次,并最后会定格在最后一帧上,要是android:oneshot属性设为 false ,那么便会无限循环地显示这三个帧。
下面的一段代码展示了如何把上面的XML配置的Animation Drawable应用到ImageView中:
- AnimationDrawable rocketAnimation;
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
- rocketImage.setBackgroundResource(R.drawable.rocket_thrust);
- rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
- }
- public boolean onTouchEvent(MotionEvent event) {
- if (event.getAction() == MotionEvent.ACTION_DOWN) {
- rocketAnimation.start();
- return true;
- }
- return super.onTouchEvent(event);
- }