**
WebViewActivity页面
**
package cj.com.a1609aproject.view.activity;
import android.util.Log;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import cj.com.a1609aproject.R;
import cj.com.a1609aproject.view.js.AndroidtoJs;
public class WebViewActivity extends BaseActivity {
private WebView webView;
private Button button;
@Override
public void initView() {
webView = findViewById(R.id.webview);
button = findViewById(R.id.button);
// button.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// webView.loadUrl("javascript:callJS()");
// }
// });
}
@Override
public void initData() {
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
//settings.setJavaScriptCanOpenWindowsAutomatically(true);
webView.addJavascriptInterface(new AndroidtoJs(), "test");//AndroidtoJS类对象映射到js的test对象
webView.loadUrl("file:///android_asset/javascript.html");
// webView.setWebChromeClient(new WebChromeClient(){
// @Override
// public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//
// Log.e("myMessage","onJsAlert "+message);
// return super.onJsAlert(view, url, message, result);
//
// }
// });
}
@Override
public int setSelfView() {
return R.layout.activity_webview;
}
}
**
weiViewActivity页面的布局
**
<?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"
android:orientation="vertical"
tools:context=".view.activity.MainActivity">
<Button
android:id="@+id/button"
android:layout_width="100dp"
android:layout_height="50dp" />
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/button">
</WebView>
</RelativeLayout>
**
AndroidtoJs接口
**
package cj.com.a1609aproject.view.js;
import android.util.Log;
import android.webkit.JavascriptInterface;
public class AndroidtoJs {
//js调用本地方法
@JavascriptInterface
public void hello(String msg) {
Log.e("myMessage","AndroidtoJs ");
}
}
**
assest文件下的html文件内容
**
<html>
<head>
<meta charset="utf-8">
<title>Carson_Ho</title>
<script>
function callJS(){
alert("Android调用了JS的callJS方法");
}
function callAndroid(){
// 由于对象映射,所以调用test对象等于调用Android映射的对象
test.hello("js调用了android中的hello方法");
}
</script>
</head>
<body>
<button type="button" style="width:200px;height:200px" id="button1" onclick="callAndroid()"></button>
</body>
</html>