public class Options extends AppCompatActivity {
MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options);
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.music01);
}
public void playSong(View view) {
CheckBox musicCheck = findViewById(R.id.musicCheck);
if (musicCheck.isChecked()) {
mediaPlayer.start();
}
else {
mediaPlayer.stop();
}
}
}
当我选中复选框时,音乐开始播放,而当我取消选中复选框时,音乐停止播放。但是,当我再次选中该复选框时,音乐不会播放。
答案 0 :(得分:2)
将此添加到onCreate
musicCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (musicCheck.isChecked()) {
mediaPlayer.start();
} else {
mediaPlayer.stop();
}
}
});