【发布时间】:2011-07-16 08:01:02
【问题描述】:
我想等到 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中似乎提到了类似的东西
代码片段
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 调用中运行我的动画。在最后一次迭代中,我使用线程表面视图来运行动画。最后一种方法是迄今为止最快和最好的(出于本文中所问的其他原因)。我希望它可以帮助某人。
【问题讨论】:
-
动画完成需要多长时间..?
-
CapDroid 如果您将上述 xml sn-p 中的所有整数相加,您将获得动画的总持续时间。但我正在寻找一个通用的解决方案,因此在这种情况下对我没有帮助。
-
试试这个 Thread.sleep(663); 663 = 动画总时间..
标签: java android concurrency android-animation