AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM不起作用

问题描述

修改:在底部更新

我在应用程序的onCreate中称其为:AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYstem)

然后,当我进入设备的设置(设置->显示->夜间模式(开关:打开/关闭))时,我将恢复我的应用程序,但该主题未应用。在设备设置中打开或关闭夜间模式都没关系,主题不会应用。

我还添加一个断点,并且检查了以下内容是否返回了false,即使从设备设置中启用了暗模式(请注意:该应用是在暗模式关闭的情况下启动的)。

fun isNightMode(app: Application): Boolean {
     return when(app.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
         Configuration.UI_MODE_NIGHT_NO -> false
         Configuration.UI_MODE_NIGHT_YES -> true
         else -> false
     }
 }

从设备设置更改主题时,application's资源似乎没有更新。

出于调试目的,我在Application类中重写了以下功能

override fun onConfigurationChanged(newConfig: Configuration?) {
   super.onConfigurationChanged(newConfig)
} 

它正在被调用

编辑:看来这是引起问题的原因。在Application类中具有此功能

override fun attachBaseContext(base: Context) {
   val locale = Locale("de","DE")

   Locale.setDefault(locale)

   val resources = base.resources
   val configuration = Configuration(resources.configuration)

   configuration.setLocale(locale)
   val baseContext = base.createConfigurationContext(configuration)
        
   super.attachBaseContext(baseContext)
}

如果我删除上面的代码,它就可以正常工作。

解决方法

只是在这里提供一个独立的答案。
感谢 @Zbarcea Christian@Prashanth

我的问题是一样的:覆盖 attachBaseContext() 方法。所以修复它像这样:

override fun attachBaseContext(cxt: Context) {
    val resources = cxt.resources
    val configuration = Configuration(resources.configuration)
    // Required for the day/night theme to work
    configuration.uiMode = Configuration.UI_MODE_NIGHT_UNDEFINED
    val baseContext = cxt.createConfigurationContext(configuration)

    // set locale and so on ...

    super.attachBaseContext(baseContext)
}