I have four switches in my BottomSheetDialogFragment. When I make DarkMode 'On', the app is recreated. 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')
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):
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:
and the image after that:
The code that reads values from sharedPref and sets switches was in the onViewCreated
method. After I put that code in onResume
method, my problem solved.