Android动画入门三---Frame Animation

Frame Animation。在前面已经说过,Frame Animation是顺序播放事先做好的图像,跟电影类似。不同于animation package, Android SDK提供了另外一个类AnimationDrawable来定义、使用Frame Animation。
Frame Animation定义的动画放到/res/drawable下面。
在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-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就定义了一个Frame Animation,其包含3帧动画,3帧动画中分别应用了drawable中的3张图片:rocket_thrust1,rocket_thrust2,rocket_thrust3,每帧动画持续200毫秒。
然后我们将以上XML保存在res/drawable/文件夹下,命名为rocket_thrust.xml
在OnCreate()中增加如下代码:
ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
rocketImage.setBackgroundResource(R.anim.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);
}
具体的AnimationDrawable类的介绍,可以参考sdk
https://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html
获取、设置动画的属性
int getDuration() 获取动画的时长
int getNumberOfFrames() 获取动画的帧数
boolean isOneShot()获取oneshot属性

Void setOneShot(boolean oneshot)设置oneshot属性
void inflate(Resurce r,XmlPullParser p,
AttributeSet attrs) 增加、获取帧动画
Drawable getFrame(int index) 获取某帧的Drawable资源
void addFrame(Drawable frame,int duration) 为当前动画增加帧(资源,持续时长)动画控制
void start() 开始动画
void run() 外界不能直接掉调用,使用start()替代
boolean  isRunning() 当前动画是否在运行
void stop() 停止当前动画

猜你喜欢

转载自ericchan2012.iteye.com/blog/1636485