Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 355
Abdelrhman Talat Avatar asked Jan 13 '20 17:01

Abdelrhman Talat


People also ask

How do I make WebView dark?

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 .

How do I force Android to dark?

Open System Settings. Navigate to Developer Options. Scroll down the Hardware accelerated rendering section and enable the Override force-dark/Force dark mode* option.

How do I make web pages darker on Android?

# 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.


1 Answers

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
like image 184
VonSchnauzer Avatar answered Oct 17 '22 00:10

VonSchnauzer