Android API Guide for Animation and Graphics(四)—— 动画与图形(帧动画)

帧动画

帧动画通过加载一个一个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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值