要在Android中调用H5中的函数或H5中调用Android中的方法,实现方式如下:
布局文件:test_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp">
<Button
android:id="@+id/btn1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="无参调用"/>
<Button
android:id="@+id/btn2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="有参调用"/>
</LinearLayout>
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="9" />
</LinearLayout>
java文件:TestActivity.java
public class TestActivity extends Activity implements View.OnClickListener {
WebView webView;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.test_activity);
//初始化控件
Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(this);
Button btn2 = (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(this);
webView = (WebView) findViewById(R.id.webView);
//获取WebSettings
WebSettings settings = webView.getSettings();
//让WebView支持js
settings.setJavaScriptEnabled(true);
//加载本地assets目录下的静态网页
webView.loadUrl("file:///android_asset/test.html");
//用于让H5调用android方法,第一个参数是传给js的对象,第二个参数是用于js调用的对象名称
webView.addJavascriptInterface(this, "androidJs");
}
@Override
public void onClick(View v) {
int i = view.getId();
if (i == R.id.btn1) {
//参数 "javascript:" + js函数名
webView.loadUrl("javascript:message1()");
} else if (i == R.id.btn2) {
String name = "Android参数";
//在android调用js有参函数的时候,参数要加单引号
webView.loadUrl("javascript:message2('" + name + "')");
}
}
//JS调用Android方法
//@JavascriptInterface注解最好添加,避免出现兼容性问题
@JavascriptInterface
public void setMessage() {
Toast.makeText(this, "无参提示", Toast.LENGTH_SHORT).show();
}
@JavascriptInterface
public void setMessage(String name) {
Toast.makeText(this, "有参提示:" + name, Toast.LENGTH_SHORT).show();
}
}
H5网页文件:test.html
<html>
<head>
<meta charset="utf-8" />
<title>H5交互测试</title>
</head>
<body>
<button id="btn1">调用android无参方法</button>
<button id="btn2">调用android有参方法</button>
</body>
<script type="text/javascript">
var name = "H5参数"
document.getElementById("btn1").onclick = function(){
//androidJs是传过来的对象名称,setMessage是android中的方法
androidJs.setMessage();
};
document.getElementById("btn2").onclick = function(){
//androidJs是传过来的对象名称,setMessage是android中的方法
androidJs.setMessage(name);
};
function message1(){
alert("调用了无参的js函数");
};
function message2(des){
alert("调用了无参的js函数:"+des);
};
</script>
</html>