1. 使用
- 1.允许WebView加载js
mWebView.getSettings().setJavaScriptEnabled(true);
- 2.编写js接口
- 3.给WebView添加js接口
mWebView.addJavascriptInterface(new JSInterface(this),"launcher");
4.加载html网页
格式为file:///android_asset/网页名.html
mWebView.loadUrl("file:///android_asset/index.html");
2.效果图
当点击点击按钮时,会将WebView中输入的值传递给TextView并显示,效果图如下所示:
3. 代码
3.1 Html代码
在main下新建assets文件夹,将html文件放入此文件夹中
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>WebView</title>
<style>
body{
background:#0094ff
}
.btn{
line-height: 40px;
margin: 10px;
background:#00ff90
}
</style>
</head>
<body>
<h2>WebView</h2>
<div><span>请输入要传递的值:</span><input type="text" id="input"/></div>
<div id="btn"><span class="btn">点击</span></div>
<script type="text/javascript">
var btn = document.getElementById("btn");
var input = document.getElementById("input");
btn.addEventListener("click", function () {
var str = input.value;
if (window.launcher) {
launcher.setValue(str)
} else {
alert("launcher not found!");
}
});
</script>
</body>
</html>
3.2 xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".web.WebViewActivity">
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="400dp" />
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/web_view"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:textSize="20sp" />
</RelativeLayout>
3.3 Java代码
JSBridge接口
public interface JSBridge {
void setTextView(String str);
}
js接口JSInterface类
public class JSInterface {
private JSBridge jsBridge;
public JSInterface(JSBridge jsBridge){
this.jsBridge = jsBridge;
}
//此方法不在主线程中执行
@JavascriptInterface //必须添加此注解,否则无法识别
public void setValue(String value){
jsBridge.setTextView(value);
}
}
Activity代码
public class WebViewActivity extends AppCompatActivity implements JSBridge {
private WebView mWebView;
private TextView mTextView;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
initWidgets(savedInstanceState);
}
@SuppressLint("SetJavaScriptEnabled")
private void initWidgets(Bundle savedInstanceState) {
mWebView = findViewById(R.id.web_view);
mTextView = findViewById(R.id.text_view);
mHandler = new Handler();
//允许WebView加载JS
mWebView.getSettings().setJavaScriptEnabled(true);
//给WebView添加JS接口
mWebView.addJavascriptInterface(new JSInterface(this),"launcher");
mWebView.loadUrl("file:///android_asset/index.html");
}
@Override
public void setTextView(String str) {
mHandler.post(() -> mTextView.setText(str));
}
}