AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM not working

1.5k views Asked by At

Edit: Updated in the bottom

I'm calling this in Application's onCreate: AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)

Then when I'm going to the device's settings (Settings -> Display -> Night mode (switch: on/off)) then I'm resuming my application, the theme is not applied. It doesn't matter if I'm turning ON or OFF the night mode in the device's settings, the theme is not applied.

I also added a breakpoint and I checked that the following is returning me false even if the Dark Mode is ON from device's settings (Note: the app was started with Dark mode OFF).

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
     }
 }

It looks like the application's resource doesn't get updated when I'm changing the theme from device settings.

For debug purpose I override the following function in the Application class:

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

and it's getting called.

Edit: It looks like this is causing the problem. Having this in the Application class:

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)
}

If I remove the code above it's working.

1

There are 1 answers

0
Mahozad On

Just to provide a standalone answer here.
Thanks to @Zbarcea Christian and @Prashanth for their comments.

The problem for me was the same: overriding attachBaseContext() method. So, fixed it like this:

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)
}