2017-05-09 107 views
0

我正在嘗試創建一個音樂應用程序。它正在Android Studio中開發。我想要這個按鈕在按下時啓動聲音,當我釋放按鈕時停止,但是我無法使它工作。Android工作室OnTouchListener

import android.media.MediaPlayer; 

import android.os.Bundle; 

import android.support.v7.app.AppCompatActivity;  

import android.view.MotionEvent; 

import android.view.View; 

import android.widget.Button; 

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     final MediaPlayer minus5 = MediaPlayer.create(this, R.raw.min5); 

     final Button play_min5 = (Button) this.findViewById(R.id.min5); 

     play_min5.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      switch (event.getAction()) { 
       case MotionEvent.ACTION_DOWN: 
        // PRESSED 
        minus5.start(); 
        return true; // if you want to handle the touch event 
       case MotionEvent.ACTION_UP: 
        // RELEASED 
        minus5.stop(); 
        return true; // if you want to handle the touch event 
      } 
      return false; 
     } 
    }); 

} 

}

+1

你是什麼意思的「不工作」? – etan

+0

該按鈕將不會按下。我可以播放聲音如果我使用Clicklistener。所以我的猜測是我寫的代碼有問題。 –

+0

你的意思是'按鈕不會按'?按鈕沒有給出它被按下的視覺指示器嗎?你的事件沒有被觸發?都? – Denny

回答

0

試試這一個。 只需寫出返回true而不是false,它就像一個魅力。

play_min5.setOnTouchListener(new View.OnTouchListener() 
{ 
    @Override 
    public boolean onTouch(View v, MotionEvent event) 
    { 
     // Your code here 
     return true; 
    } 
});