Android错误在夜间模式下加载错误的颜色

odi*_*ity 4 android webview android-night-mode

免责声明:我已经找到了解决此问题的方法,但由于我花了很长时间才弄清楚它为什么会发生,所以我想将问题和答案发布给其他人。

我遇到一个奇怪的问题:在夜间模式下打开应用程序时,某些UI会以正确的夜间模式颜色加载,而某些UI会以正常颜色加载。

odi*_*ity 6

事实证明,存在一个奇怪的错误,即只有一次创建WebView时,它才会重置UI模式。所以对我来说,发生的是:

-初始化应用程序,并在其上设置夜间模式-
在初始活动中以适当的颜色
加载某些UI-进行异步调用以获取内容-
在辅助片段中创建WebView,重置UI模式-
异步调用返回,以普通模式加载UI元素

解决方案(我在这里找到)是在应用程序启动时初始化一个虚拟的WebView,该虚拟WebView在启用夜间模式之前没有在任何地方使用,以便下次使用WebView时不会重置UI模式。所以像这样:

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)
        }
  }
}
Run Code Online (Sandbox Code Playgroud)