我无法切换onoff的键值。为什么每次点击按钮(声音(时键值都没有改变?默认的onoff值为0,单击按钮,onoff值应更改为1。但它不能。为什么?
private var mp: MediaPlayer? =null
var sound_onoff:Int=0
onCreat{...
mp= MediaPlayer.create(this, R.raw.key_tone)
val pref = applicationContext.getSharedPreferences("MyPref", 0)
val editor = pref.edit()
sound_onoff = pref.getInt("onoff", 0)
sound.setOnClickListener{
when(sound_onoff){
1->{sound.setText("SOUND ON")
mp?.setVolume(1F,1F)
mp!!.start()
editor.putInt("onoff", 0)
editor.apply()}
0->{sound.setText("SOUND OFF")
mp?.setVolume(0F,0F)
mp!!.start()
editor.putInt("onoff", 1)
editor.apply()}
}
}
我建议您使用布尔值而不是Int.
以及为什么你的代码不起作用。因为您只将sound_onoff = pref.getInt("onoff", 0)
放在onCreate中,所以它在创建类时只调用一次。
当你需要检查时,你需要调用sound_onoff = pref.getInt("onoff", 0)
。
试试这个:
sound.setOnClickListener{
sound_onoff = pref.getInt("onoff", 0)
when(sound_onoff){
1->{sound.setText("SOUND ON")
mp?.setVolume(1F,1F)
mp!!.start()
editor.putInt("onoff", 0)
editor.apply()}
0->{sound.setText("SOUND OFF")
mp?.setVolume(0F,0F)
mp!!.start()
editor.putInt("onoff", 1)
editor.apply()}
}
}
希望得到帮助!