First of all you need to add android.webkit dependency into your project
dependencies {
implementation "androidx.webkit:webkit:1.3.0"
}
At the time of writing this post the latest stable version of webkit is 1.3.0.
It is worth noting that the Dark Theme support has been added with version 1.2.0, before this version it was impossible to add Dark Theme support to Webview.
Next step would be to check whether Webview and Android framework on user’s device supporting theming:
if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
...
}
Please note that WebViewFeature.FORCE_DARK
is only supported starting with Webview version 76. Unfortunately before that version there is no straightforward way to support the dark theming.
If you own the contents displayed within the Webview you might want to implement your custom CSS themes and toggle them using @JavascriptInterface from your app.
If WebViewFeature.FORCE_DARK
is supported we can choose from three available options:
FORCE_DARK_OFF - Disable dark theme, the content will be rendered in default Light Theme
FORCE_DARK_ON - Enable dark theme, the content will be rendered in Dark Theme
FORCE_DARK_AUTO - Enable dark theme based on the state of parent view
Then we need to apply the setting using WebSettingsCompat
WebSettingsCompat.setForceDark(webView.settings, WebSettingsCompat.FORCE_DARK_ON)
You can read about in more detail in the below blogpost
https://androidexplained.github.io/ui/android/material-design/2020/09/24/dark-mode-webview.html