MyAnimationDrawable _animaition = new MyAnimationDrawable(); Drawable frame; Bitmap bmp; int n = filesNames.length; for (int i = 0; i < n; i++) { bmp = BitmapFactory.decodeResource(getResources(), filesNames[i]); frame = new BitmapDrawable(getResources(), bmp); _animaition.addFrame(frame, 100); }
//控制帧动画的时间,函数重写 public class MyAnimationDrawable extends AnimationDrawable {
private volatile int duration;//its volatile because another thread will update its value private int currentFrame;
public MyAnimationDrawable() { currentFrame = 0; }
@Override public void run() { int n = getNumberOfFrames(); currentFrame++; if (currentFrame >= n) { currentFrame = 0; } selectDrawable(currentFrame); scheduleSelf(this, SystemClock.uptimeMillis() + duration); }
public void setDuration(int duration) { this.duration = duration; //we have to do the following or the next frame will be displayed after the old duration unscheduleSelf(this); selectDrawable(currentFrame); scheduleSelf(this, SystemClock.uptimeMillis()+duration); } }
然后就可以调用上面实现的函数了:_animaition.setDuration(speed);
speed为自定义时间/速度参数。
最后启动动画:
1 2 3 4 5 6 7 8
//是否仅仅启动一次? _animaition.setOneShot(false); if (_animaition.isRunning()) { //是否正在运行? _animaition.stop(); //停止 } _animaition.start();//启动