Monday 4 October 2021

Injecting CSS into Webview

XML
==========================================================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
tools:context=".MainActivity"
android:orientation="vertical"
>

<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>

</LinearLayout>
==========================================================


JAVA
===========================================================

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebActivity2 extends AppCompatActivity {

WebView webView;

private String style;
private final static String CREATE_CUSTOM_SHEET =
"if (typeof(document.head) != 'undefined' && typeof(customSheet) == 'undefined') {"
+ "var customSheet = (function() {"
+ "var style = document.createElement(\"style\");"
+ "style.appendChild(document.createTextNode(\"\"));"
+ "document.head.appendChild(style);"
+ "return style.sheet;"
+ "})();"
+ "}";
DisplayMetrics displayMetrics = new DisplayMetrics();


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_web2);

// setTitle("360 degree View Test");
webView = (WebView) findViewById(R.id.webView);

getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
style= "#wr360PlayerId {"+
"width: 100%;"+
"height: 100% !important;"+
"}";

showWebPage();
}



private void showWebPage(){
String sURL = "https://www.eichertrucksandbuses.com/360/PRO-6042/exterior/PRO-6042.html";
webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setSupportZoom(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);

webView.loadUrl(sURL);
}

private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}

@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
injectCssIntoWebView(view, style);
}

@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
new WebActivity2().showDialog("Oops", "Something went wrong");
}

}

private void showDialog(String title, String msg){
webView.setVisibility(View.INVISIBLE);
new AlertDialog.Builder(WebActivity2.this)
.setTitle(title)
.setMessage(msg)
.setCancelable(false)
.setIcon(android.R.drawable.ic_dialog_alert)
.setNegativeButton("Retry", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
webView.setVisibility(View.VISIBLE);
showWebPage();
}
})
.setPositiveButton("Back", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
onBackPressed();
}
})
.show();
}


private void injectCssIntoWebView(WebView webView, String... cssRules) {
StringBuilder jsUrl = new StringBuilder("javascript:");
jsUrl
.append(CREATE_CUSTOM_SHEET)
.append("if (typeof(customSheet) != 'undefined') {");
int cnt = 0;
for (String cssRule : cssRules) {
jsUrl
.append("customSheet.insertRule('")
.append(cssRule)
.append("', ")
.append(cnt++)
.append(");");
}
jsUrl.append("}");
System.out.println("### JS: "+jsUrl.toString());
webView.loadUrl(jsUrl.toString());
}


}
===========================================================

AndroidManifest.xml
===========================================================
<activity android:name=".WebActivity2"
android:screenOrientation="landscape"
android:theme="@style/Theme.AppCompat.NoActionBar"
/>
===========================================================


22

No comments:

Post a Comment