Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android bug loading wrong colors in night mode

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.

like image 759
odiggity Avatar asked Jan 15 '19 02:01

odiggity


1 Answers

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

like image 180
odiggity Avatar answered Sep 30 '22 13:09

odiggity