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

来源:互联网 发布:sql server 2000精简版 编辑:程序博客网 时间:2024/05/02 02:11

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是如何使用的。

这里写图片描述

0 0
原创粉丝点击