0

I'm working on a soundboard and I want to implement a long click to share the sound.

I am working with a switch Case for each button

 public void MainMMP(View view){
    switch (view.getId()) {
        case R.id.button1:
                MainMMP.release();
                MainMMP = MediaPlayer.create(this, R.raw.xxx1);
                MainMMP.start();
                break;
        case R.id.button2:
                MainMMP.release();
                MainMMP = MediaPlayer.create(this, R.raw.xxx2);
                MainMMP.start();
                break;
        case R.id.button3:
            MainMMP.release();
            MainMMP = MediaPlayer.create(this, R.raw.xxx3);
            MainMMP.start();
            break;

And now I want to implement the long click. I tried a lot of different code here but it is not working for me. I do not know where to put the onLongClick statement and how.

Can somebody show me a working method and in case of long click it should just send me a Toast that I know the method works?

Glenn Slayden
  • 17,543
  • 3
  • 114
  • 108
ExiizZ
  • 59
  • 1
  • 6

2 Answers2

0

You could add the OnLongClickListener where you want, in the onCreate method for example.

Try to use the following code:

    Button button = (Button)findViewById(R.id.button);
    button.setOnLongClickListener(new View.OnLongClickListener() {

    @Override
    public boolean onLongClick(View v) {

        //Your code

        return false; // True if you want to execute simple click code too
    }
});
Juanje
  • 1,235
  • 2
  • 11
  • 28
0

You can use this

    private View.OnLongClickListener listener = new View.OnLongClickListener() {

    @Override
    public boolean onLongClick(View view) {
        switch (view.getId())
           case R.id.button1:
             // Do something...
             break;
           case R.id.button2:
             // Do something else...
             break;
        // If you still want to get normal click callbacks return true,
        // if you do not then return false.
        return true; 
    }
}

Somewhere in your code

Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnLongClickListener(listener);
button2.setOnLongClickListener(listener);

Or better this

One common recommended way to get onClick/onLongClick/whatever callbacks is to make the Activity implement the callback interfaces.

class YourActivity extend Activity implements View.OnLongClickListener {

    @Override
    public boolean onCreate(/* ... */) {
        // ...
        button1.setOnLongClickListener(this);
        button2.setOnLongClickListener(this);
    }

    @Override
    public boolean onLongClick(View view) {
        // Same code as the one above
    }
}