WebView重置UiMode并打破黑暗主题

时间:2019-08-15 20:37:49

标签: android android-webview android-theme android-dark-theme

我们的应用依靠AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)来使我们从values/colorsvalues-night/colors拾取浅色和深色主题颜色

但是,每次我们尝试使用WebView时,它都会从重置UiMode开始,我们的应用程序会感到困惑,以便为主题选择哪种颜色值

有人herehere详细讨论了这个问题

有人在那里遇到类似的问题吗?

3 个答案:

答案 0 :(得分:1)

回答我自己的问题,好像Google已解决问题https://issuetracker.google.com/issues/37124582

https://developer.android.com/jetpack/androidx/releases/appcompat#1.1.0-alpha03 Fixed WebView resets DayNight Resources

答案 1 :(得分:0)

在上一期期刊关闭时,我打开了新的期刊:https://issuetracker.google.com/issues/170328697

我试图用这种方式修复它:

class UiModeCareWebView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : WebView(context, attrs, defStyleAttr) {

    init {
        fixUiModeIfNeeded()
    }

    private fun fixUiModeIfNeeded() {
        val configuration = context.resources.configuration
        val configurationNighMode = configuration.uiMode and UI_MODE_NIGHT_MASK
        val appCompatNightMode = getDefaultNightMode()

        val newUiModeConfiguration = when {
            configurationNighMode == UI_MODE_NIGHT_NO && appCompatNightMode == MODE_NIGHT_YES -> {
                UI_MODE_NIGHT_YES or (configuration.uiMode and UI_MODE_NIGHT_MASK.inv())
            }
            configurationNighMode == UI_MODE_NIGHT_YES && appCompatNightMode == MODE_NIGHT_NO -> {
                UI_MODE_NIGHT_NO or (configuration.uiMode and UI_MODE_NIGHT_MASK.inv())
            }
            else -> null
        }

        if (newUiModeConfiguration != null) {
            val fixedConfiguration = Configuration().apply {
                uiMode = newUiModeConfiguration
            }
            @Suppress("DEPRECATION")
            context.resources.updateConfiguration(
                fixedConfiguration,
                context.resources.displayMetrics
            )
        }
    }
}

答案 2 :(得分:0)

首先,您需要在项目中添加android.webkit依赖项

dependencies {
   implementation "androidx.webkit:webkit:1.3.0"
}

在撰写本文时,最新的Webkit稳定版本是1.3.0。 值得注意的是,在版本1.2.0中已添加了对深色主题的支持,在此版本之前,无法在Webview中添加深色主题的支持。

下一步是检查用户设备上的Webview和Android框架是否支持主题:

if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
   ...
}

请注意,WebViewFeature.FORCE_DARK仅从Webview版本76开始受支持。不幸的是,在该版本之前,没有直接的方法来支持深色主题。 如果您拥有显示在Webview中的内容,则可能需要实现自定义CSS主题并使用应用程序中的@JavascriptInterface对其进行切换。

如果支持WebViewFeature.FORCE_DARK,我们可以从三个可用选项中进行选择:

FORCE_DARK_OFF -禁用深色主题,将以默认的浅色主题呈现内容 FORCE_DARK_ON -启用深色主题,内容将以深色主题呈现 FORCE_DARK_AUTO -根据父视图的状态启用深色主题 然后我们需要使用WebSettingsCompat来应用设置

WebSettingsCompat.setForceDark(webView.settings, WebSettingsCompat.FORCE_DARK_ON)

您可以在下面的博客文章中详细了解

https://androidexplained.github.io/ui/android/material-design/2020/09/24/dark-mode-webview.html