views:

93

answers:

1

the following code is to handle ACTION_DOWN and ACTION_UP events for a button named clash. the idea is that once if/else determines that the onTouch event was caused by clash and the switch statement then determines what to do based on the action. i don't know if the problem is that the switch statements are not returning true and that may be related to the problem. when i add a return, eclipse says that the code is unreachable which i don't understand. i was under the impression that you can't break out of a switch without break.

what's actually happening is that the first sound will loop but the code never seems to detect the action up when the button is released and so the sound plays forever. any help would be appreciated.

 public boolean onTouch(View v, MotionEvent event) {
 MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.raw.clash);
 if (v.getId() == R.id.clash){

 switch (event.getAction()){

 case MotionEvent.ACTION_DOWN:
  mp.setLooping(true);
  mp.start();
   break;

 case MotionEvent.ACTION_UP:
  mp.pause();
  break;
 }

}
return true;
}
   });
+2  A: 
//Add the following line in the code before your setOnTouchListener()
MediaPlayer mp;

public boolean onTouch(View v, MotionEvent event) { 

    if (v.getId() == R.id.clash){ 

        switch (event.getAction()) { 

        case MotionEvent.ACTION_DOWN: 
            mp = MediaPlayer.create(getBaseContext(), R.raw.clash); 
            mp.setLooping(true); 
            mp.start(); 
            break; 

        case MotionEvent.ACTION_UP: 
            if(mp != null) 
            {
                mp.pause(); 
                mp.release();
            }
            break; 
        } 
    } 
} 

// I'm assuming this was from the onTouchListener()? -> }); 

Just a thought.

kcoppock
that works out just fine. thanks a lot, man. it was a basic problem but i couldn't for the life of me get it right.
strangeInAStrangerLand
No problem! Glad that worked for you.
kcoppock