-1

我的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 开关重新创建应用程序之前我的控件: 在此处输入图像描述

以及之后的图像:

在此处输入图像描述

4

1 回答 1

0

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

于 2021-01-09T07:25:09.210 回答