我是android编程的新手。我有以下代码,但我有问题。当我单击搜索栏而不播放声音时,它会强制关闭。我的意思是,当我单击播放按钮时,我可以单击并在搜索栏上搜索,但不单击播放按钮,单击搜索栏会导致强制关闭。有什么问题?!
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity implements Runnable, OnClickListener, OnSeekBarChangeListener{
private SeekBar seekBar;
private ImageButton startMedia;
private ImageButton pauseMedia;
private MediaPlayer mp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AudioControl();
}
public void AudioControl(){
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (ImageButton) findViewById(R.id.playbutton);
pauseMedia = (ImageButton) findViewById(R.id.pausebutton);
seekBar.setOnSeekBarChangeListener(this);
startMedia.setOnClickListener(this);
pauseMedia.setOnClickListener(this);
}
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(startMedia)) {
if (mp != null && mp.isPlaying()) return;
if(seekBar.getProgress() > 0) {
mp.start();
return;
}
mp = MediaPlayer.create(MainActivity.this, R.raw.lone);
mp.start();
seekBar.setProgress(0);
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
if (v.equals(pauseMedia) && mp!=null) {
mp.pause();
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(fromUser) mp.seekTo(progress);
}
}
我还有另一个问题:我想当用户点击播放按钮时暂停按钮变得可见,当用户点击暂停按钮时它变得不可见。我应该写什么代码,请告诉我应该把这段代码放在哪里。