2017-05-09 122 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; 
    } 
});