Frame-by-frame Animation可以在XML Resource定义(存放到res/anim文件夹下,也可以存放在res/drawable文件夹下(Android文档就是这样说的)),也可以使 用AnimationDrawable中的API定义。由于Tween Animation与Frame-by-frame Animation有着很大的不同,因此XML定义的格式也完全不一样,其格式是:首先是animation-list根节点,animation- list根节点中包含多个item子节点,每个item节点定义一帧动画:当前帧的drawable资源和当前帧持续的时间。下面对节点的元素加以说明:
XML属性 | 说明 |
drawable | 当前帧引用的drawable资源 |
duration | 当前帧显示的时间(毫秒为单位) |
oneshot | 如果为true,表示动画只播放一次停止在最后一帧上,如果设置为false表示动画循环播 放。 |
variablePadding | If true, allows the drawable’s padding to change based on the current state that is selected. |
visible | 规定drawable的初始可见性,默认为flase; |
动画文件animation.xml为:
<?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="true"> <item android:drawable="@drawable/appwidget_clock_dial" android:duration="2000"></item> <item android:drawable="@drawable/clockdroid2_dial" android:duration="2000"></item> <item android:drawable="@drawable/clockdroids_dial" android:duration="2000"></item> <item android:drawable="@drawable/clockgoog_dial" android:duration="2000"></item> </animation-list>
主文件FrameAnimation.java为:
package com.android.animation; import android.app.Activity; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.view.MotionEvent; import android.widget.ImageView; public class FrameAnimation extends Activity { AnimationDrawable frameAnimation = new AnimationDrawable(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setBackgroundResource(R.anim.animation); frameAnimation = (AnimationDrawable)imageView.getBackground(); } @Override public boolean onTouchEvent(MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN) { frameAnimation.start(); } return super.onTouchEvent(event); } }
几点说明:
- animation.xml中<?xml version="1.0" encoding="utf-8"?>是必不可少的,它标识版本号和编码类型。
- animation.xml中xmlns:android="http://schemas.android.com/apk/res/android"也是必不可少的,缺失会提示“
Error parsing XML: unbound prefix
”的错误。它指定正确的namespace。 - 与Tween animation的动画文件相比,在<animation-list></animation-list>标签外面少了<set></set>标签,如果加上程序不能运行。<set>: A container that can recursively hold itself or other animations.You can include as many child elements of the same or different types as you like.关于资源方面的详细标签介绍参考file:///work/android-sdk-linux_x86-1.6_r1/docs/guide/topics/resources/available-resources.html 。里面有动画标签的详细说明。
- 启动Frame-by-frame Animation动画的代码FrameAnimation.start();不能在OnCreate()中,因为在OnCreate()中AnimationDrawable还没有完全的与ImageView绑定,在OnCreate()中启动动画,就只能看到第一张图片。