我在Android中使用首选项。当我更改开关时,我会输入一个布尔值:
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
switch1.setOnCheckedChangeListener{_, isChecked ->
if(isChecked){
sharedPref?.let {
with(it.edit()) {
putBoolean("sw1", true)
apply()
}
}
}else{
sharedPref?.let {
with(it.edit()) {
putBoolean("sw1", false)
apply()
}
}
}
}
我明白了:
val sw1 = sharedPref?.getBoolean("sw1", false)
sw1?.let {
switch1.isChecked = sw1
}
但我收到一个错误:
java.lang.ClassCastException:java.lang.Integer无法强制转换为java.lang.Boolean
如果共享首选项中的数据是使用putInt((存储的,而getBoolean((用于检索相同键的数据,则会发生ClassCastException。
它可以通过两种方式解决。
-
可以清除共享的首选项数据。从"设置"->"应用程序信息"->"您的应用程序"->"清除数据"。
-
如果需要将首选项数据类型更改为布尔型,请确保在getBoolean((之前调用putBoolean(。