Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering event when Button is pressed down in Android

Tags:

android

button

I have the following code for Android which works fine to play a sound once a button is clicked:

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 upon pressing the button (touch down), not when it is released (touch up). Any ideas on how I can accomplish this?

like image 346
codeman Avatar asked Apr 11 '10 00:04

codeman


3 Answers

You should 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;
            }
        });
like image 94
Macarse Avatar answered Nov 12 '22 00:11

Macarse


Maybe using a OnTouchListener? I guess MotionEvent will have some methods for registering a touch on the object.

   button.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
     // TODO Auto-generated method stub
     return false;
    }
   }))
like image 23
Peterdk Avatar answered Nov 12 '22 00:11

Peterdk


import android.view.MotionEvent;

like image 3
tomanesq Avatar answered Nov 11 '22 23:11

tomanesq