(1)html代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Android/Javascript互调Demo</title>
<script type="text/javascript" language="javascript">
function callJavaScriptMethod()
{
document.getElementById("content").innerHTML = "Android 调用 Javascript 成功";
}
</script>
</head>
<body>
<div ><a onClick="window.demo.callJavaMethod()" href="">点击-->JS调用Android代码</a></div>
<div style="margin:50px 50px 50px 50px;" id="content"></div>
</body>
</html>
(2)android代码
Android_xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/androidCallJSBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击 Android 调用 JavaScript"/>
</LinearLayout>
Android java代码:
private void initView() {
mWebView = (WebView) findViewById(R.id.webview);
WebSettings mWebSettings = mWebView.getSettings();
mWebSettings.setJavaScriptEnabled(true); //加上这句话才能使用javascript方法
mWebView.addJavascriptInterface(new Object() {//增加接口方法,让html页面调用
@JavascriptInterface
public void callJavaMethod() {
Toast.makeText(getApplicationContext(), "JS调用Android成功", Toast.LENGTH_LONG).show();
}
}, "demo");
mWebView.loadUrl("file:///android_asset/demo.html"); //加载页面
androidCallJSBtn = (Button) findViewById(R.id.androidCallJSBtn);
androidCallJSBtn.setOnClickListener(new Button.OnClickListener() { //给button添加事件响应,执行JavaScript的fillContent()方法
public void onClick(View v) {
mWebView.loadUrl("javascript:callJavaScriptMethod()");
}
});
}
下面详解:
在html body中div中写一个a标签,也就是超链接。
div是一个块级元素。这意味着它的内容自动地开始一个新行。实际上,换行是div 固有的唯一格式表现。可以通过 div的 class 或 id 应用额外的样式。
id指的是类型也就是内容。
<script type="text/javascript" language="javascript">
function callJavaScriptMethod()
{
document.getElementById("content").innerHTML = "Android 调用 Javascript 成功";
}
</script>
js代码,主要是给内容添加一行内容,内容为Android调用Javascript成功。
java调用js的代码主要是这句:
androidCallJSBtn.setOnClickListener(new Button.OnClickListener() { //给button添加事件响应,执行JavaScript的fillContent()方法
public void onClick(View v) {
mWebView.loadUrl("javascript:callJavaScriptMethod()");
}
});
js调用Android的代码是这句:
mWebView.addJavascriptInterface(new Object() {//增加接口方法,让html页面调用
@JavascriptInterface
public void callJavaMethod() {
Toast.makeText(getApplicationContext(), "JS调用Android成功", Toast.LENGTH_LONG).show();
}
}, "demo");
前提是:加上这句, mWebSettings.setJavaScriptEnabled(true); //加上这句话才能使用javascript方法,这样就可以了。