How do I set a function to repeat until a Button is pressed
Given the following code:
package com.buttonsound;
imp开发者_如何学Cort android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class buttonsound extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final MediaPlayer mpButton=MediaPlayer.create(this,R.raw.button_click);
Button buttonsound=(Button) findViewById(R.id.button1);
buttonsound.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent me) {
while(me.getAction()==MotionEvent.ACTION_DOWN)
{
mpButton.start();
}
return false;
}
});
}
}
How do I start a function and set it to repeat until a Button is pressed which terminates the operation. The above code simply repeats even after the button is released.
You're never calling stop()
, of course it'll keep playing. Your while loop is calling start()
multiple times, you shouldn't be doing that. Think of it like any other Media Player -- you don't continually press Play to listen to the whole track, it continues until you tell it otherwise.
Try something like this instead:
public boolean onTouch(View v, MotionEvent me) {
switch(me.getAction()) {
case MotionEvent.ACTION_DOWN:
if(!mpButton.isPlaying()) mpButton.start();
break;
case MotionEvent.ACTION_UP:
if(mpButton.isPlaying()) mpButton.stop();
break;
}
}
EDIT: As an aside, naming a MediaPlayer mpButton
is just asking for confusion down the line; just sayin'. ;)
hi you can do something like this :
Boolean btnIsPressed = false;
Button btn = (Button) findViewById(R.id.btn);
and add a thread , and in the method run add this code :
@Override
public void run(){
while(!btnIsPressed){
myfunction();
}
}
finally , in your method onCreate , add a listener to change the value of your boolean to true like this :
btn.addOnClickListener( new OnClickListener(){
@Overrride
public void onClick(View v){
btnIsPressed = true;
}
});
Hope it helps
if you're talking about how to repeat something in mediaplayer just
mediaPlayer.seekTo(0);
mediaPlayer.start();
精彩评论