2012-03-10 179 views
3

我正在移動圖像,並且想在對象的動畫完成後播放聲音文件
圖像移動,但我嘗試使用線程來等待,直到持續時間但它不起作用。Android等待動畫完成

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

謝謝。

回答

7

可以爲動漫登記委託:

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

-1

建議你

  • 創建一個對象來封裝「動畫」一生
  • 在對象中,你將有一個線程或一個定時器
  • 提供方法來啓動()的動畫和awaitCompletion()
  • 使用私人最終對象completionMonitor現場跟蹤完成後,就可以進行同步,並使用wait() and 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,並捕捉動畫作爲一個可贖回的每一幀。提交Callables序列並使用invokeAll() or a CompletionService來阻止感興趣的線程,直到動畫完成。

+0

http://stackoverflow.com/a/5321508/779982 – naugler 2013-12-08 15:02:40