我想等到 Android ImageView 中的动画完成*后再继续执行程序,这样做的正确方法是什么?
- (在这种情况下,“完成”意味着它恰好遍历所有帧并在最后一帧停止。我不清楚这个动画是否会是一个 android:oneshot="true"动画,因为我会多次使用它,但它不会连续运行而是间歇性运行)
研究/猜测:
A.从本质上讲,我的问题似乎是一个 Java 线程问题,因为 Android AnimationDrawable实现 Java.lang.Runnable .所以也许线程是解决方案。也许答案将包括join ?
B.其他人的方法似乎是使用AnimationListener ,对于我的简单需求,这似乎很困难且不必要的复杂。另外,我不确定该怎么做。
C. AnimationDrawable类有一个 (boolean) isRunning 方法,它可能会在 while 循环中使用(即 while(anim.isRunning()){wait(100ms)})。但我有一种直觉,这是错误的方法。虽然 concurrency tutorial 中似乎提到了类似的东西
代码 fragment
this.q_pic_view.setImageResource(0);
this.q_pic_view.setBackgroundResource(R.drawable.animation_test);
AnimationDrawable correct_animation = (AnimationDrawable) this.q_pic_view.getBackground();
correct_animation.start();
//here I tried to implement option C but it didn't work
while(correct_animation.isRunning()){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
动画
<?xml version="1.0" encoding="utf-8"?>
<animation-list android:id="@+id/AnimTest" android:oneshot="true" xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/animtest001" android:duration="33"/>
<item android:drawable="@drawable/animtest002" android:duration="100"/>
<item android:drawable="@drawable/animtest003" android:duration="66"/>
<item android:drawable="@drawable/animtest004" android:duration="66"/>
<item android:drawable="@drawable/animtest005" android:duration="33"/>
<item android:drawable="@drawable/animtest006" android:duration="66"/>
<item android:drawable="@drawable/animtest007" android:duration="33"/>
<item android:drawable="@drawable/animtest008" android:duration="66"/>
<item android:drawable="@drawable/animtest009" android:duration="100"/>
<item android:drawable="@drawable/animtest010" android:duration="100"/>
</animation-list>
实现预期效果的一种可能方法是通过执行以下操作来延迟进一步代码的执行,尽管这不是我的问题的答案:
int duration = 0;
//Add all of the frames together
for (int i=0; i<my_animation.getNumberOfFrames(); i++){
duration = duration + correct_animation.getDuration(i);
}
//delay the execution
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
public void run() {
DoYourNextStuff();
}
}, duration); //delay is here
编辑:有很多方法可以解决这个问题,给出的答案可能确实解决了问题我没有测试它,但我最终只是等待了正确的时间(起初),然后我改为使用异步任务(它有一个完成的处理程序方法)并直接在异步任务的 updateProgress 调用中运行我的动画。在最后一次迭代中,我使用线程表面 View 来运行动画。最后一种方式是迄今为止最快和最好的(除了本文中提到的其他原因)。我希望它可以帮助某人。
最佳答案
最简单的方法是将(延迟的)Runnable 发布到 UI 线程:
Animation fadeout = new AlphaAnimation(1.f, 0.f);
fadeout.setDuration(500);
view.startAnimation(fadeout);
view.postDelayed(new Runnable() {
@Override
public void run() {
view.setVisibility(View.GONE);
}
}, 500);
这样可以轻松完成这项工作。并且从不(从不,从不,从不!)尝试阻塞 Android 中的 UI 线程。如果你这样做了,手机就会死机,无论如何你都看不到动画。 如果您需要等待一段时间,请使用另一个线程。
关于java - 安卓动画: Wait until finished?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5321344/