1.加载网页html
android.webkit.WebView webView =findViewById(R.id.wb_view);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true); //设置WebView属性,运行执行js脚本
webSettings.setRenderPriority(WebSettings.RenderPriority.LOW); //禁用硬件加速
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.loadUrl(path);
2.加载本地html
创建assert目录
创建html文件和图片目录
book.html内容
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<meta charset="utf-8">
<div class="neirong" id="mytext" style="font-size: 18px">
替换
</div>
</div>
</body>
<script src="jquery.min.js"></script>
<script type="text/javascript">
function showtext(data){
$("#mytext").html(data);
}
</script>
</html>
activity_w1.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"
android:orientation="vertical"
tools:context=".W1">
<WebView
android:id="@+id/w1"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_weight="1"/>
</LinearLayout>
加载本地html支持html里加载assert下的文件,支持java调用html里的js方法
package com.example.book2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.InputStream;
//WebView加载html工具类
public class W1 extends AppCompatActivity {
private android.webkit.WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_w1);
webView = findViewById(R.id.w1);
//webSettings详细设置可以看https://blog.csdn.net/qq_41466437/article/details/103284132?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522171841822416800184128506%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=171841822416800184128506&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-5-103284132-null-null.142^v100^pc_search_result_base4&utm_term=webSettings.setAllowUniversalAccessFromFileURLs%28true%29&spm=1018.2226.3001.4187
WebSettings webSettings = webView.getSettings();
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
//用于java调用html里的js方法
webSettings.setJavaScriptEnabled(true);
//设置编码方式
webSettings.setDefaultTextEncodingName("utf-8");
// 确保WebView有访问网络的权限
webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
// 设置WebViewClient来处理页面加载事件(可选)
webView.setWebViewClient(new WebViewClient() {
//当页面加载完成
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//替换文章内容
callEvaluateJavascript(webView);
}
//如果html里的图片资源是本地的话可以用这个指定图片资源
@Override
public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest) {
String url = webResourceRequest.getUrl().toString();
String key = "toimg/data";
/*如果请求包含约定的字段 说明是要拿本地的图片*/
if (url.contains(key)) {
// 假设图片在assets/toimg/data/目录下,并且文件名是5909889921.png
String fileName = url.substring(url.lastIndexOf('/') + 1); // 提取文件名
InputStream inputStream = null; // 使用AssetManager打开文件
try {
if (!fileName.contains(".png"))
return super.shouldInterceptRequest(webView, webResourceRequest);
inputStream = getAssets().open("toimg/data/" + fileName);
} catch (Exception e) {
e.printStackTrace();
}
// 创建一个WebResourceResponse对象来返回文件数据
return new WebResourceResponse("image/png", "UTF-8", inputStream);
}
return super.shouldInterceptRequest(webView, webResourceRequest);
}
});
webView.loadUrl("file:///android_asset/html/book.html");
}
//在html加载完成后调用html里的showtext替换文章内容
private void callEvaluateJavascript(WebView webView) {
String data = escapeJavaScriptString("<div>文章内容<div>");
System.out.println(data);
webView.evaluateJavascript("javascript:showtext(\"" + data + "\")", null);
}
//将java的String的数据转换成html可以加载的String数据
public static String escapeJavaScriptString(String input) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
switch (c) {
case '"':
sb.append("\\\"");
break;
case '\'':
sb.append("\\'");
break;
case '\\':
sb.append("\\\\");
break;
case '/':
// 通常不需要转义斜杠,但在某些上下文中可能需要
sb.append("\\/");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
default:
if (Character.isISOControl(c)) {
// 对于ISO控制字符,可能需要更复杂的处理或替换
// 这里只是简单地用一个占位符替换,您可以根据需要修改
sb.append("\\u").append(String.format("%04X", (int) c));
} else {
sb.append(c);
}
}
}
return sb.toString();
}
}