Trigger event when button is pressed in Android

I have the following Android code that works great to play sound after a button is pressed:

Button SoundButton2 = (Button)findViewById(R.id.sound2);
        SoundButton2.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        mSoundManager.playSound(2);

    }
});

My problem is that I want the sound to play immediately after pressing the button (tapping down), and not when releasing (tap). Any ideas on how I can do this?

+23
source share
3 answers

Maybe with help OnTouchListener? I think MotionEvent will have some methods for registering object touches.

   button.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
     // TODO Auto-generated method stub
     return false;
    }
   }))
+18
source

You must do this: b is the button.

b.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN ) {
                    mSoundManager.playSound(2);
                    return true;
                }

                return false;
            }
        });
+29
source

import android.view.MotionEvent;

+3
source

All Articles