Insert or inject stylesheet css to Android webview java
You can stylize or modify webpages with your own custom CSS style sheet in Android webview. To do that, we need a stylesheet.css and a few lines of code.
In the below code, we will inject a css in the webview of Android after it finishes loading a website, but how do we know if a web page has finished loading already? Yes we can, with the onPageFinished method of Android.
This is the method that gets invoked once the Android webview finishes loading a website so we can do some custom action
@Override
public void onPageFinished(WebView view, String url)
Injecting the CSS into Webview after finish loading
First, put your css file inside the assets folder, rename your css to black or change the css name to your css name in the below code
@Override public void onPageFinished(WebView view, String url) { // Inject CSS when page is done loading injectCSS(); super.onPageFinished(view, url); } }); // Load a webpage webl.loadUrl("http://www.google.com"); } // Inject CSS method: read style.css from assets folder // Append stylesheet to document head private void injectCSS() { try { InputStream inputStream = getAssets().open("black.css"); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer); inputStream.close(); String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP); webl.loadUrl("javascript:(function() {" + "var parent = document.getElementsByTagName('head').item(0);" + "var style = document.createElement('style');" + "style.type = 'text/css';" + // Tell the browser to BASE64-decode the string into your script !!! "style.innerHTML = window.atob('" + encoded + "');" + "parent.appendChild(style)" + "})()"); } catch (Exception e) { e.printStackTrace(); };
The above code injects the CSS from assets folder (black.css) to webview after it has been loaded. i use this code for setting a night mode in my app. you need define the load url twice, first define it above the shouldOverrideUrlLoading method, then in the onpagefinished method (already defined in the code above)
A user requested the Black.css file, so here is it
Update: If you are new to android development, or just want fix this error or other android app development errors, i can fix those for you for a reasonable small fee. Just send me your project or that java file (The Activity where you wish to add this code) through email or google drive, i will fix your project or file and send it back to you.
Can you pls provide black.css file. Thanks
Yes i uploaded it