MainActivity.java:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = findViewById(R.id.web);
String webUrl = "<p><img class=\"wscnph\" src=\"https://zkw.oss-cn-beijing.aliyuncs.com/mall/images/5f2421586efc4816ae355b4064f49b34.jpg\" /></p>";
String JS = "<head>\n" +
"<meta name=\"viewport\" content=\"width=device-width, user-scalable=no\" />\n" +
"<style>p{margin:0}body{margin-left:0.1; margin-top:0.7; margin-right:0.1; margin-bottom:1;}img{width:100%; height:auto;}</style>\n" +
"</head>";
WebSettings settings = webView.getSettings();
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
settings.setJavaScriptEnabled(true);//支持JS
settings.setDisplayZoomControls(false);
settings.setDomStorageEnabled(true);
settings.setDomStorageEnabled(true);
settings.setUseWideViewPort(true);
settings.setMediaPlaybackRequiresUserGesture(false);
new Thread(new Runnable() {
@Override
public void run() {
String regx = "<img( )?[a-zA-Z0-9.:\\\"' //=;%/,!_()-\uFE30-\uFFA05]+(/)?>";
Pattern p = Pattern.compile(regx);
Matcher matcher = p.matcher(webUrl);
StringBuilder sb = new StringBuilder();
while (matcher.find()) {
sb.append(matcher.group());
}
String content = sb.toString().replace("style", "").replace("align", "");
runOnUiThread(new Runnable() {
@Override
public void run() {
webView.loadDataWithBaseURL(null, "<html>" + JS + "<body>" + webUrl + "</body>" + "</html>",
"text/html", "utf-8", null);
}
});
}
}).start();
}
}
AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
activity_main.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/web" />
</LinearLayout>