2010-10-13 102 views
0

下面的代碼是處理名爲clash的按鈕的ACTION_DOWN和ACTION_UP事件。這個想法是,一旦if/else確定onTouch事件是由衝突引起的,並且switch語句根據該動作確定要執行的操作。我不知道是否問題是switch語句沒有返回true,並且可能與問題有關。當我添加一個返回時,eclipse說代碼無法訪問,我不明白。我的印象是,你不能沒有休息地突破開關。問題if/else和switch語句

實際發生的事情是,第一個聲音會循環播放,但是當釋放按鈕時代碼從未檢測到動作,所以聲音永遠播放。任何幫助,將不勝感激。

public boolean onTouch(View v, MotionEvent event) { 
MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.raw.clash); 
if (v.getId() == R.id.clash){ 

switch (event.getAction()){ 

case MotionEvent.ACTION_DOWN: 
    mp.setLooping(true); 
    mp.start(); 
    break; 

case MotionEvent.ACTION_UP: 
    mp.pause(); 
    break; 
} 

} 
return true; 
} 
    }); 
+0

即使添加「返回true」後我仍然沒有得到任何行動。在這種情況下,我甚至可以讓代碼播放聲音,而不是採取行動,它什麼也不做。 – Prmths 2010-10-13 19:51:42

+3

我不確定這一點,但是不會在每次按OR釋放時創建新的MediaPlayer對象嗎?在這種情況下,你會在不同的MediaPlayer實例上調用'pause()'而不是調用'start()'? – kcoppock 2010-10-13 20:04:18

+0

確實有意義。問題是,當我將mp的創建移動到處理ACTION_DOWN事件的邏輯部分時,沒有任何反應。它根本不播放任何聲音。我開始考慮徹底放棄MediaPlayer,因爲每次播放聲音時都必須創建並銷燬對象。我做的每一個搜索都說你不能動態設置數據源。 – Prmths 2010-10-13 20:14:18

回答

3
//Add the following line in the code before your setOnTouchListener() 
MediaPlayer mp; 

public boolean onTouch(View v, MotionEvent event) { 

    if (v.getId() == R.id.clash){ 

     switch (event.getAction()) { 

     case MotionEvent.ACTION_DOWN: 
      mp = MediaPlayer.create(getBaseContext(), R.raw.clash); 
      mp.setLooping(true); 
      mp.start(); 
      break; 

     case MotionEvent.ACTION_UP: 
      if(mp != null) 
      { 
       mp.pause(); 
       mp.release(); 
      } 
      break; 
     } 
    } 
} 

// I'm assuming this was from the onTouchListener()? -> }); 

只是一個想法。

+0

,工作得很好。非常感謝,夥計。這是一個基本的問題,但我不能爲我的生活得到它的權利。 – Prmths 2010-10-13 21:10:34

+0

沒問題!很高興爲你工作。 – kcoppock 2010-10-13 21:19:32