[英]SwitchCompats are checked incorrectly after Dark/Light Mode recreates the app
I have four switches in my BottomSheetDialogFragment .我的BottomSheetDialogFragment中有四个开关。 When I make DarkMode 'On', the app is recreated.
当我将 DarkMode 设置为“开启”时,会重新创建应用程序。 The weird thing is that other switches became 'On' even if those were 'Off' before.
奇怪的是,即使之前是“关闭”,其他开关也变成了“打开”。 (The value in SharedPref is 'false' but the Switch shows 'on')
(SharedPref 中的值为 'false' 但 Switch 显示为 'on')
I use this code to make switches on/off when dialog is created:创建对话框时,我使用此代码打开/关闭开关:
binding.autoPlaySwith.setOnCheckedChangeListener(null)
binding.autoPlaySwith.isChecked = getHawkBoolean(AUTO_PLAY_VIDEO) //read it from sharedPref
binding.autoPlaySwith.setOnCheckedChangeListener(this)
//same code for other switches
And this code for switches checkedChange event(The problem occurs in DarkMode checked on/off):这段代码用于切换checkedChange事件(问题发生在DarkMode检查开/关):
override fun onCheckedChanged(view: CompoundButton, isChecked: Boolean) {
if (view.isPressed) {
when (view.id) {
binding.autoPlaySwith.id -> {
saveHawkBoolean(AUTO_PLAY_VIDEO, isChecked)
}
binding.themeSwith.id-> {
saveHawkBoolean(DARK_MODE, isChecked)
try {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
} catch (ex: Exception) {
Log.d(TAG , ex.localizedMessage?:"exception occurred ")
}
}
}
}
}
my Controls before recreate the app via DarkMode switch:在通过 DarkMode 开关重新创建应用程序之前我的控件:
and the image after that:以及之后的图像:
The code that reads values from sharedPref and sets switches was in the onViewCreated
method.从 sharedPref 读取值并设置开关的代码位于
onViewCreated
方法中。 After I put that code in onResume
method, my problem solved.在我将该代码放入
onResume
方法后,我的问题就解决了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.