Skip to content

Commit

Permalink
Use built-in tools for darkmode if supported
Browse files Browse the repository at this point in the history
  • Loading branch information
92lleo committed Oct 4, 2022
1 parent 1b1c9ee commit 7504d9a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 10 deletions.
1 change: 1 addition & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,5 @@ android {
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.webkit:webkit:1.4.0'
}
28 changes: 18 additions & 10 deletions app/src/main/java/io/kuenzler/whatsappwebtogo/WebviewActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,15 @@
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.webkit.WebSettingsCompat;
import androidx.webkit.WebViewFeature;

import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;

import java.util.Arrays;
import java.util.Locale;
import java.util.Objects;

public class WebviewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

Expand Down Expand Up @@ -567,17 +570,22 @@ private void loadWhatsapp() {
}

public void addDarkMode(final WebView mWebView) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setNavigationBarColor(Color.BLACK);
getWindow().setStatusBarColor(Color.BLACK);
try{ getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.BLACK));
} catch (NullPointerException ignored) {}
}
getWindow().setNavigationBarColor(Color.BLACK);
getWindow().setStatusBarColor(Color.BLACK);

mWebView.loadUrl("javascript:(" +
"function(){ " +
"try { document.body.classList.add('dark') } catch(err) { }" +
"})()");
Objects.requireNonNull(getSupportActionBar()).setBackgroundDrawable(new ColorDrawable(Color.BLACK));

if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
WebSettingsCompat.setForceDark(mWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK_STRATEGY)) {
WebSettingsCompat.setForceDarkStrategy(mWebView.getSettings(), WebSettingsCompat.DARK_STRATEGY_PREFER_WEB_THEME_OVER_USER_AGENT_DARKENING);
}
} else {
mWebView.loadUrl("javascript:(" +
"function(){ " +
"try { document.body.classList.add('dark') } catch(err) { }" +
"})()");
}
}

public void setContentSize(final WebView mWebView){
Expand Down

0 comments on commit 7504d9a

Please sign in to comment.