帧动画
帧动画通过加载一个一个Drawable资源文件来实现动画。这个典型的动画就像播放电影一样,按顺序播放不同的图片。AnimationDrawable类是帧动画的基类。
你可以使用AnimationDrawable类在你的代码中声明一个帧动画,然而,通过一个单独的xml文件来实现帧动画更加简单。这种动画类型xml文件需要存放于Android项目的res/drawable/目录下。在xml布局中声明的每一帧都是按时长以及顺序执行的。
xml文件由<animatin-list>根节点以及一系列声明了一帧的<item>子节点(一个drawable资源)组成,下面示例帧动画的xml文件。
<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>
这个动画仅仅有3帧。通过设置animation-list的android:oneshot属性为true,动画将执行一次然后停止并保持在最后一帧的状态。如果设置为false,那么动画将一直循环下去。将此xml文件存放于项目res/drawable/目录下的rocket_thrust.xml后,它可以作为一个View的背景图并播放这个动画。下面是一个将该动画添加到ImageView并在触碰屏幕的时候播放的Activity示例:
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);
}
有一点要提示的是start()方法不能在Activity的onCreate()方法中调用,因为AnimationDrawable还没有完全绑定到window上。如果你想在还没交互的情况下立即执行动画,你可能需要通过在Activity中调用当Android聚焦你的window时的方法onWindowFocusChange()。
获取更多xml的属性语法,请参看Animation Resource.
原文链接:https://developer.android.google.cn/guide/topics/graphics/drawable-animation.html