最近的项目中遇到了客户端编程与html 公用的情况,所以免不了会用到html中js与客户端的编程,所以研究了一下,希望与大家共享!
其实实现该功能的帖子网上一大堆,在这里我只说重点。
第一:不管你采用本地加载WebView 还是网络地址,只要在初始化webView 的时候添加如下代码即可:
webView.addJavascriptInterface(this, "<span style="color:#33ccff;background-color: rgb(255, 255, 255);">android</span>");
两个参数,第一个参数是为javaScript设置上下文,第二个参数其实就是用来标识调用者的Key.(个人理解)
下面我们写一个方法来响应javaScript中的Action
<pre class="html" name="code"><pre class="html" name="code">/** 与js交互时用到的方法,在js里直接调用的 */
@JavascriptInterface
public void <span style="color:#ff0000;">startFunction</span>(String str) {
Intent intent = new Intent();
intent.putExtra("str", str);
intent.setClass(this, SecondActivity.class);
startActivity(intent);
}
@JavascriptInterface
public void <span style="color:#ff0000;">startFunction</span>() {
Intent intent = new Intent();
intent.setClass(this, SecondActivity.class);
startActivity(intent);
}
可以看到以上两个方法一个是有参数的,一个是无参数的.
我们在写一个方法用来向js发起action
<pre class="html" name="code"> findViewById(R.id.bt).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 无参数调用
webView.loadUrl("javascript:<span style="color:#cc33cc;">javacalljs</span>()");
// // 传递参数调用
webView.loadUrl("javascript:<span style="color:#cc33cc;">javacalljswithargs</span>("
+ "'hello world'" + ")");
}
});
至此客户端编程基本上完事了,下面我们看一下html页面的js怎么写。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script type="text/javascript">
function <span style="color:#cc33cc;">javacalljs</span>(){
document.getElementById("content").innerHTML +=
"<br\>java调用了js函数";
}
function <span style="color:#cc33cc;">javacalljswithargs</span>(arg){
document.getElementById("content").innerHTML +=
("<br\>"+arg);
}
</script>
</head>
<body>
this is my html <br/><br/><br/>
<a onClick="window.<span style="color:#33ccff;">android.</span><span style="color:#ff0000;">startFunction</span>()">点击调用java代码</a><br/><br/><br/>
<a onClick="window.<span style="color:#33ccff;">android</span>.<span style="color:#ff0000;">startFunction</span>('传参--hello world')" >点击调用java代码并传递参数</a>
<br/><br/><br/>
<div id="content">内容显示</div><br/><br/>
</body>
</html>
如上代码需要注意的地方我都已经加了颜色标记了,一看就明白了吧 !
附上代码:<a target=_blank href="http://download.csdn.net/detail/qq446869111/8236569">http://download.csdn.net/detail/qq446869111/8236569</a>