7

Disclaimer: I have already found a solution to this problem but wanted to post the question and answer for other people since it took me a long time to figure out why it was happening.

I ran into a strange issue where when opening my application in night mode, some of the UI was loaded in the correct night mode colors and some of the UI was loaded in the normal colors.

odiggity
  • 1,496
  • 16
  • 29

1 Answers1

12

It turns out there is a strange bug where only the first time a WebView is created, it resets the UI mode. So for me, what was happening was:

-Application is initialized and night mode is set on
-Some of the UI is loaded in the initial activity with the proper colors
-Asynchronous call is made to fetch content
-WebView is created in a secondary fragment, resetting the UI mode
-Asynchronous call returns, loading UI elements in normal mode

The solution (which I found here), is to initialize a dummy WebView when the application starts up that isn't used anywhere before enabling night mode, so that the next time a WebView is used it won't reset the UI mode. So something like this:

class MyApplication : Application() {
  
  override fun onCreate() {
        super.onCreate()
        val nightModeEnabled = //get value from shared prefs or wherever you are storing this flag
        if (nightModeEnabled) {
            Timber.d("Manually instantiating WebView to avoid night mode issue.");
            try {
                WebView(applicationContext)
            } catch (e: Exception) {
                Timber.e("Got exception while trying to instantiate WebView to avoid night mode issue. Ignoring problem.", e)
            }
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
        }
  }
}

Edit Looks like they may have fixed this in Appcompat Version 1.1.0-alpha03 (haven't actually tried it though) "Fixed WebView resets DayNight Resources (b/37124582)"

odiggity
  • 1,496
  • 16
  • 29
  • 1
    This fixed things but recently we noticed it was causing crashes on Samsung devices with Android P. You can see the crash reported here https://stackoverflow.com/questions/44035654/broken-colors-in-daynight-theme-after-loading-admob-firebase-ad Did you experience a similar crashes? – display name Aug 15 '19 at 15:02
  • I'm using Appcompat 1.1.0 and the problem persists with that. Maybe they backed out the fix in the released version? – chrisbtoo Oct 16 '20 at 17:38
  • Hello from 2021: Even with AppCompat 1.3.0 this is still required. – SebastianBrandt May 28 '21 at 22:38
  • webview init inside application class, will affect application init performance. it will took about 200ms. – changhao cui Jan 28 '23 at 04:42
  • @SebastianBrandt Hello from 2023: AppCompat 1.6.1 - bug still exists. – Ololoking Jul 10 '23 at 16:12