I can't seem to be able to get android web view to use dark theme or use
@media (prefers-color-scheme: dark)
I am using AndroidX with DayNight theme
Does anyone has a solution that is backward compatible before api 29?
Use FORCE_DARK_AUTO mode WebView and all its parents can allow force dark using View. setForceDarkAllowed() . The default value is taken from the setForceDarkAllowed() attribute of the Android theme, which must also be set to true .
Open System Settings. Navigate to Developer Options. Scroll down the Hardware accelerated rendering section and enable the Override force-dark/Force dark mode* option.
# On an Android phone Navigate to chrome://flags and enable the #darken-websites-checkbox-in-theme-setting experiment. Then, tap the three dots menu, select Settings then Theme, and check the box with Apply Dark themes to sites, when possible.
Add to your app's build.grade:
implementation "androidx.webkit:webkit:1.2.0"
You can check the latest version to use here:
https://developer.android.com/jetpack/androidx/releases/webkit
If you have a class that extends WebView, then add this in your extending class' constructor:
public MyWebView(Context context, AttributeSet attrs) {
super(context, attrs);
...
if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
WebSettingsCompat.setForceDark(getSettings(), WebSettingsCompat.FORCE_DARK_ON);
}
...
}
If you have an activity that that instantiates a webview, add this to the activity's onCreate method:
myWebView = getViewById(R.id.web_content);
if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
WebSettingsCompat.setForceDark(myWebView.getSettings(),
WebSettingsCompat.FORCE_DARK_ON);
}
Of course, you might want to decide which force strategy you want:
WebSettingsCompat.FORCE_DARK_ON
WebSettingsCompat.FORCE_DARK_OFF
WebSettingsCompat.FORCE_DARK_AUTO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With