在Android ImageView中等待动画完成后才能继续程序执行,正确的方法是什么?
- (在这种情况下,“完成”意味着它恰好运行所有帧一次,并停止在最后一个帧上。我不清楚这个动画是否是android:oneshot =“ true”动画,因为我将多次使用它,但它不会连续运行而是间歇性地运行)
研究/猜测:
A. 本质上,我的问题似乎是一个Java线程问题,因为Android AnimationDrawable 实现了Java.lang.Runnable。因此,也许线程是解决方案。也许答案会包括join?
B. 其他人的方法似乎是使用AnimationListener,这对于我的简单需求来说似乎很困难和复杂。另外我不太确定该如何做。
C. AnimationDrawable类有一个(布尔值)isRunning方法,可以在while循环中使用(即while(anim.isRunning(){wait(100ms)})。但是我有一种直觉认为这是错误的方法。尽管类似的内容似乎在并发教程中提到过。
代码片段
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调用中运行我的动画。在最后一次迭代中,我使用了一个线程表面视图来运行动画。这种方式迄今为止是最快和最好的(除了本帖子所询问的原因之外)。我希望它能帮助到某些人。