Frame动画
其实就是逐帧动画,用法也比Tween动画简单,只需要创建一个AnimationDrawable对象来表示Frame动画,然后通过addFrame方法把每一帧要显示的内容加进去就行了,最后通过start方法就可以播放这个动画了,通过还可以使用
setOneShot()方法
来设置动画是否重复播放。
最后在程序中通过setBackgroundResource方法加载这个XML动画布局文件,通过getBackground方法得到动画,通过setBackgroundDrawable方法设置要显示的动画,通过start方法启动播放。
再这里,还需要设置图片的所在位置,首先要在res/anim目录下创建一个xml配置文件,用于存放图片资源的索引,配置的是一个以<animation-list>根原素和<item>子元素。
下面我们可以使用xml布局文件来实现Frame动画。首先在xml文件通过oneshot设置动画是否重复播放,然后加所有的帧都列出来。如下代码:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">
<item android:drawable="@drawable/a1" android:duration="800"/>
<item android:drawable="@drawable/a2" android:duration="800"/>
<item android:drawable="@drawable/a3" android:duration="800"/>
<item android:drawable="@drawable/a4" android:duration="800"/>
<item android:drawable="@drawable/a5" android:duration="800"/>
<item android:drawable="@drawable/a6" android:duration="800"/>
<item android:drawable="@drawable/a7" android:duration="800"/>
<item android:drawable="@drawable/a8" android:duration="800"/>
<item android:drawable="@drawable/a9" android:duration="800"/>
<item android:drawable="@drawable/a10" android:duration="800"/>
<item android:drawable="@drawable/a11" android:duration="800"/>
<item android:drawable="@drawable/a12" android:duration="800"/>
<item android:drawable="@drawable/a13" android:duration="800"/>
<item android:drawable="@drawable/a14" android:duration="800"/>
<item android:drawable="@drawable/a15" android:duration="800"/>
</animation-list>
最后在程序中通过setBackgroundResource方法加载这个XML动画布局文件,通过getBackground方法得到动画,通过setBackgroundDrawable方法设置要显示的动画,通过start方法启动播放。
package com.hanfeng.view;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.view.View;
import android.widget.ImageView;
public class GameView extends View {
/*定义AnimationDrawable动画对象*/
private AnimationDrawable frameanim = null;
Context context = null;
public GameView(Context context) {
super(context);
this.context = context;
/*定义一个ImageView用来显示动画*/
ImageView img = new ImageView(context);
/*状态布局文件*/
img.setBackgroundResource(R.drawable.frame_animation);
/*构建动画*/
frameanim = (AnimationDrawable)img.getBackground();
/*设置是否循环*/
frameanim.setOneShot(false);
/*设置该类显示的动画*/
this.setBackgroundDrawable(frameanim);
/*启动播放*/
frameanim.start();
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new GameView(this);
setContentView(gameView);
}