android webView开发之js调用java代码示例

 1.webView设置

webView.getSettings().setJavaScriptEnabled(true);//设置支持js
webView.addJavascriptInterface(new JsOperation(),"client");//设置js调用的java类


2.声明js要调用java类

class JsOperation {

// 测试方法
@JavascriptInterface//这句标识必须要写上否则会出问题
public void test(String param) {
Toast.makeText(MainActivity.this,param,Toast.LENGTH_SHORT).show();

}
}

3.在js中调用java类中的方法

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>测试</title>
<script type="text/javascript">
function test(param){
client.test(param);调用java中的方法
}

</script>
</head>
<body>
<br />
<button onclick="test('js调用java方法')">test</button>
</body>
</html>

posted @ 2016-07-31 10:17  猿哥爱码  阅读(1260)  评论(0编辑  收藏  举报