tags:

views:

784

answers:

2

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?

A: 

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;
    }
   }))
Peterdk
Thanks for the response. Got the following errors when trying to use that code:- The type new View.OnTouchListener(){} must implement the inherited abstract method View.OnTouchListener.onTouch(View, MotionEvent)- The method onTouch(View, MotionEvent) of type new View.OnTouchListener(){} must override a superclass method- MotionEvent cannot be resolved to a type
sw333t
+2  A: 

You should do this: b is the button.

b.setOnTouchListener(new OnTouchListener() {

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

                return false;
            }
        });
Macarse
Still getting these errors:- The type new View.OnTouchListener(){} must implement the inherited abstract method View.OnTouchListener.onTouch(View, MotionEvent) - The method onTouch(View, MotionEvent) of type new View.OnTouchListener(){} must override a superclass method - MotionEvent cannot be resolved to a type
sw333t
The code supplied in both of these answers appears to be correct. Add an import to `android.view.MotionEvent`. Here is the documentation for `OnTouchListener`: http://developer.android.com/reference/android/view/View.OnTouchListener.html
CommonsWare
Nice, got it to work after importing MotionEvent and using this line:if (event.getAction() == MotionEvent.ACTION_DOWN ) {
sw333t