Android等待动画完成

4

我正在移动一张图片,希望在对象的动画完成后播放音频文件。
图片已经移动,但我尝试使用线程等待一段时间,但并没有成功。

Animation animationFalling = AnimationUtils.loadAnimation(this, R.anim.falling);
iv.startAnimation(animationFalling);
MediaPlayer mp_file = MediaPlayer.create(this, R.raw.s1);
duration = animationFalling.getDuration();
mp_file.pause();
new Thread(new Runnable() {
    public void run() {
        try {
            Thread.sleep(duration);
            mp_file.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
  }).start();

感谢您的选择。
2个回答

8
您可以为动画注册委托函数:
animationFalling.setAnimationListener(new AnimationListener() {

     @Override
     public void onAnimationStart(Animation animation) {    
     }

     @Override
     public void onAnimationRepeat(Animation animation) {
     }

     @Override
     public void onAnimationEnd(Animation animation) {
           // here you can play your sound
     }
);

您可以在这里阅读更多关于AnimationListener的内容


-1

建议你

  • 创建一个对象来封装“动画”生命周期
  • 在对象中,你将拥有一个线程或者计时器(Timer)
  • 提供方法来启动动画并且awaitCompletion()
  • 使用一个私有常量对象completionMonitor字段来追踪完成情况,在其上进行同步,并使用wait()和notifyAll()来协调awaitCompletion()

代码片段:

final class Animation {

    final Thread animator;

    public Animation()
    {
      animator = new Thread(new Runnable() {
        // logic to make animation happen
       });

    }

    public void startAnimation()
    {
      animator.start();
    }

    public void awaitCompletion() throws InterruptedException
    {
      animator.join();
    }
}

你也可以使用一个单线程的 ThreadPoolExecutor 或者 ScheduledThreadPoolExecutor,并将每一帧动画作为一个 Callable。将这些 Callable 序列提交,并使用 invokeAll() 或 CompletionService 来阻塞你感兴趣的线程,直到动画完成。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接