本文介绍了如何仅用一个按钮即可播放和暂停-Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的媒体播放器中有两个按钮,用于广播电台,播放和暂停.我只想使它具有两个功能的一个按钮.首先单击我要播放它,然后单击我要暂停它.当我再次单击它时,我想播放它.我需要帮助.这是我的代码.
I have two buttons in my media player that streams a radio station, play and pause. I want to make it only one button that has two function. First click I want to play it and second click I want to pause it. And when I click it again I want to play it. I need help. Here is my code.
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
play.performClick();
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pause();
}
});
}
private void play() {
Uri myUri = Uri.parse("Shoutcast URL");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
@Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}
private void pause() {
mp.pause();
}
@Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
推荐答案
仅创建一个Button并添加诸如buttonstatus之类的内容.然后,您可以在侦听器中检查状态.
例如:
Create just one Button and add something like a buttonstatus. Then you can check the status in your listener.
For example:
boolean isPlaying = false;
playPause = (Button) findViewById(R.id.play);
playPause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (isPlaying) {
pause();
}else{
play();
}
isPlaying = !isPlaying;
}
});
这篇关于如何仅用一个按钮即可播放和暂停-Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!