微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

暗/亮模式重新创建应用程序后,SwitchCompats 检查不正确

如何解决暗/亮模式重新创建应用程序后,SwitchCompats 检查不正确

我的 BottomSheetDialogFragment 中有四个开关。当我将 DarkMode 设为“开启”时,应用程序会重新创建。奇怪的是,其他开关变成了“开”,即使它们之前是“关”的。 (SharedPref 中的值为 'false' 但 Switch 显示为 'on')

我使用此代码在创建对话框时打开/关闭开关:

binding.autoplaySwith.setonCheckedchangelistener(null)
binding.autoplaySwith.isChecked = getHawkBoolean(AUTO_PLAY_VIDEO) //read it from sharedPref
binding.autoplaySwith.setonCheckedchangelistener(this)

//same code for other switches

开关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 ")
                    }
                }
       }
     }
  }

我在通过 DarkMode 开关重新创建应用程序之前的控件:

enter image description here

以及之后的图像:

enter image description here

解决方法

从 sharedPref 读取值并设置开关的代码位于 onViewCreated 方法中。在我将该代码放入 onResume 方法后,我的问题解决了。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。