再次选中复选框后音乐无法播放

时间:2019-02-19 12:22:41

标签: java android android-mediaplayer

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();
        }
    }
}

当我选中复选框时,音乐开始播放,而当我取消选中复选框时,音乐停止播放。但是,当我再次选中该复选框时,音乐不会播放。

1 个答案:

答案 0 :(得分:2)

将此添加到onCreate

musicCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (musicCheck.isChecked()) {
            mediaPlayer.start();
        } else {
            mediaPlayer.stop();
        }
    }
});