最近在做个小项目的时候,需要用到帧动画。对应着某种状态,该动画可以停止和再次播放。我们知道,通过函数
总的来说,就是重新加载了一下动画背景,使得帧动画得以重置。但是在Andorid 5.0以下的版本,好像没效果。不知道具体原因是什么,后来在网上Google到有另一种方法:
someAnimObj.start()
someAnimObj.stop()
可以很容易地实现这两种需求,但是如果单纯这样做的话,会出现一个问题:第二次播放的第一帧竟然是上次停止播放时候的最后一帧
搜索了一下,发现这个是Android帧动画的通病。现把解决方法写出来。
android 5.0以上的版本
Drawable drawable = mHeaderImage.getDrawable(); ((AnimationDrawable) mHeaderImage.getDrawable()).stop(); mHeaderImage.setImageDrawable(null); mHeaderImage.setImageDrawable(drawable);
android 5.0以下的版本
The API is a bit weird here, because the restart function is inside the setVisible function of AnimationDrawable. If you don't restart and just do another start()
on an already finished animation - it will just jump to the last frame. You must reset the animation before starting it.
However if you do setVisible(true,true)
your animation will run twice!, so you must dosetVisible(false,true);
. This will reset the animation for a start()
operation.
ImageView animateHere = (ImageView) findViewById(R.id.animate_here); animateHere.setImageDrawable(((ImageView)findViewById(R.id.anim_preloaded_imgview).getDrawable()); AnimationDrawable anim = (AnimationDrawable) animateHere.getDrawable(); anim.setVisible(false, true); //reset! see previous section anim.start(); //now good to start, even if already fired before
这种方法在5.0以上有没有效果了。所以把这两种方法都用上,就可以兼容这两个版本了。