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;
}
//此方法不在主線程中執(zhí)行
@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));
}
}