4

编辑:在底部更新

我在应用程序中调用它onCreateAppCompatDelegate.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)
}

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

4

1 回答 1

2

只是在这里提供一个独立的答案。
感谢@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)
}
于 2021-04-01T11:56:34.040 回答