Android应用开发——Animation Drawable

AnimationDrawable可以让你把一系列的图片像幻灯片一样一张一张地显示在屏幕上。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()方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值