Abdelrhman Talat
Abdelrhman Talat

Reputation: 1317

Using dark mode with a webview

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?

Upvotes: 6

Views: 5561

Answers (2)

VonSchnauzer
VonSchnauzer

Reputation: 951

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

Upvotes: 7

Alex Barceló
Alex Barceló

Reputation: 322

For devices running below Android 10, you could add the androidx.webkit dependency and set your webview settings as it follows:

if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
    WebSettingsCompat.setForceDark(myWebView.settings, WebSettingsCompat.FORCE_DARK_ON)
}

Upvotes: 0

Related Questions