Android应用开发——Animation Drawable

来源:互联网 发布:2017色情交友软件 编辑:程序博客网 时间:2024/06/05 04:06

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);}
Notice:AnimationDrawable的start()方法不能在Activity.onCreate()中调用,因为那时候AnimationDrawable还没有完全地附着到window上来。如果想要自动地让AnimationDrawable播放图片,可以在Activity.onWindowFocusChanged()方法中调用start()方法。

原创粉丝点击