标签:android javascript 源码 js
<html>
<body>
<script language="javascript">
function javaCallJsFunction(isHide) {
var x = document.getElementById(‘div‘);
x.className = "";
}
function js2java() {
JSInterface.javaFunction();
}
</script>
<style type="text/css">
.hide {
display: none;
}
</style>
<input type="button" onClick="js2java()"
style="height: 200px; width: 200px" value="Call Java Fn">
<div class="hide" id="div">
<font color="#FF0000">this is a hide div~~~~</font>
</div>
</body>
function js2java() {
JSInterface.javaFunction();
}
其中JSInterface是native类的别名,相当于Java中的实例,javaFunction是native类里边声明的方法;注意一点是Android API 17及以上版本需要在方法需要声明注解@JavascriptInterface。
-Java接收JS调用和调用示例代码
public class JsInterface {
private WebView mWebView;
public JsInterface(WebView webView) {
this.mWebView = webView;
}
@JavascriptInterface
public void javaFunction() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
//update UI in main looper, or it will crash
Toast.makeText(mWebView.getContext(), "javaFunction had been called", Toast.LENGTH_SHORT).show();
}
});
}
public void javaCallJsFunction(int code){
mWebView.loadUrl(String.format("javascript:payError("+code+")"));
}
}
最后给上示例项目的源码:Android-JS-Call
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:android javascript 源码 js
原文地址:http://blog.csdn.net/cj_star/article/details/48035089