我在活动菜单中有这两个选项
选项一启动音乐曲目,选项二应该停止,但不是。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
MediaPlayer mpSoundTrack = MediaPlayer.create(this, R.raw.app_score);
switch (item.getItemId()) {
case R.id.icon: Toast.makeText(this, "Music On!", Toast.LENGTH_LONG).show();
mpSoundTrack.start();
break;
case R.id.icontext: Toast.makeText(this, "Music Off!", Toast.LENGTH_LONG).show();
mpSoundTrack.stop();
break;
}
return true;
}
答案 0 :(得分:3)
每次创建新的mediaPlayer时,都要停止新的,而不是旧的。你应该保留它的参考:
private MediaPlayer mpSoundTrack = null;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.icon:
Toast.makeText(this, "Music On!", Toast.LENGTH_LONG).show();
mpSoundTrack = MediaPlayer.create(this, R.raw.app_score);
mpSoundTrack.start();
break;
case R.id.icontext:
Toast.makeText(this, "Music Off!", Toast.LENGTH_LONG).show();
if(mpSoundTrack != null)
mpSoundTrack.stop();
break;
}
return true;
}