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();
}
}
}
When I check the checkbox, the music starts playing and when I uncheck the checkbox, the music stops playing. However, when I check the checkbox again the music does not play.
Add this in onCreate
musicCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (musicCheck.isChecked()) {
mediaPlayer.start();
} else {
mediaPlayer.stop();
}
}
});