7

免责声明:我已经找到了解决此问题的方法,但想为其他人发布问题和答案,因为我花了很长时间才弄清楚为什么会发生这种情况。

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

4

1 回答 1

12

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

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

解决方案(我在此处找到)是在启用夜间模式之前在应用程序启动时初始化一个未在任何地方使用的虚拟 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)
        }
  }
}

编辑 看起来他们可能已经在 Appcompat 版本 1.1.0-alpha03 中修复了这个问题(虽然还没有真正尝试过)“Fixed WebView resets DayNight Resources (b/37124582)”

于 2019-01-15T02:20:32.030 回答