您的位置:首页 > 移动开发 > Android开发

混合APP开发的套路(三): android和javascript初步交互(js调安卓)

2017-04-01 15:51 519 查看
http://blog.csdn.net/github_26672553/article/details/68944631

前面我们实现了,在安卓里调用 js代码。

现在我们来看看,js里如何调用android里的方法。

首先,我们在Activitity里(我们这是WebViewActivity.java),定义一个方法

@JavascriptInterface
public void setText(final String txt){
// 在另一个线程处理
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textView = (TextView)findViewById(R.id.wvText);
textView.setText(txt);
}
});
}


定义好这个方法之后,还需要其他设置才行

// 给webView添加一个js接口(本类的,名字叫abc的)
webView.addJavascriptInterface(this,"abc");


2、网页部分

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>this is title</title>
<script>
function show(){
document.getElementById("txtMsg").value = "hello javascript";
}

function setAndroidText(){
var getValue = document.getElementById("txtMsg").value;
window.abc.setText(getValue);
}
</script>
</head>
<body>
<input type="text" id="txtMsg">
<button onclick="setAndroidText()"> click me</button>
</body>
</html>


点击”click me”按钮就会调用
setAndroidText()
这个js函数,

这个js函数中调用了android里定义的
setText()
方法。

注意看明白:代码里的
abc
,这个我们在Android里定义了,在js是如何使用的。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: