概述:Drawable Animation 可以通过一个接一个(one after another) 的方式加载一系列的Drawable resources 实现动画,实际作用可以用来通过这种方式制作进度条,进度条由多张图片轮流播放视觉上形成进度条的效果。
实际操作:
在目录res/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>
很明显该xml的结构是以<animation-list>为跟节点,子节点由<item>构成定义该帧的drawable resource和停留时间(duration)。
在
<animation-list>属性中设置了 android:oneshot属性值为true,及该动画只循环一次,并且最后停留在最后一帧。如果设置成false 那么动画将一直循环,对于圆形进度条来讲应该设置成false。
该xml可以被设置成view的背景图片,通过代码来启动动画。示例如下:
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还没完全
附着(fully attached)在window上。如何你希望在不需要交互的情况下立即启动动画你可以在Activity的onWindowFocusChanged()方法中调用start()方法。which will get called when Android brings your window into focus.