【问题标题】:Android wait till animation is completedAndroid 等到动画完成
【发布时间】:2012-03-10 20:11:40
【问题描述】:

我正在移动一个图像,我想在对象的动画完成后播放一个声音文件
图像移动了,但我尝试使用 Threads 等待一段时间,但它不起作用。

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();

谢谢。

【问题讨论】:

    标签: java android android-animation


    【解决方案1】:

    你可以为动画注册一个代理:

    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 的更多信息here

    【讨论】:

      【解决方案2】:

      建议你

      • 创建一个对象来封装“动画”生命周期
      • 在对象中,您将拥有一个线程或一个计时器
      • 提供 start() 动画和awaitCompletion() 的方法
      • 使用私有最终对象completionMonitor 字段来跟踪完成情况,对其进行同步,并使用wait() and notifyAll() 来 协调 awaitCompletion()

      代码sn-p:

      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();
          }
      }
      

      您也可以使用带有单线程的ThreadPoolExecutorScheduledThreadPoolExecutor,并将动画的每一帧捕获为可调用对象。提交 Callables 序列并使用invokeAll() or a CompletionService 阻塞您感兴趣的线程,直到动画完成。

      【讨论】:

        猜你喜欢
        • 2011-07-16
        • 2015-07-17
        • 2013-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-09
        • 1970-01-01
        • 2015-10-03
        相关资源
        最近更新 更多