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

来源:互联网 发布:百度网盘下载助手mac 编辑:程序博客网 时间:2024/05/01 23:08

我们测试方便,我们利用布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent">    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="测试文本"        android:id="@+id/wvText"/>    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="调用javscript"        android:id="@+id/wvBtn"/>    <WebView        android:layout_width="match_parent"        android:layout_height="227dp"        android:layout_weight="0.27"        android:id="@+id/webView"/></LinearLayout>

我们会吧本地index.html文件加载到WebView 控件中,然后点击Button 控件,执行一段javascsript脚本(一个js方法).

index.html内容如下:

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

show() 方法实现了,把hello javascript 写入到input文本框。
我们要在安卓里来调用这个show() 方法。

Activity里:

    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        this.setContentView(R.layout.webview); // 设置layout        // 获取webView组件        final WebView webView = (WebView)findViewById(R.id.webView);        // 拿到webView的设置对象        WebSettings settings = webView.getSettings();        settings.setAppCacheEnabled(true); // 开启缓存        settings.setJavaScriptEnabled(true); // 开启javascript支持        // 加载文件到webView        AssetManager assetManager = this.getAssets();        try {            InputStream inputStream = assetManager.open("index.html");            byte[] buffer = new byte[inputStream.available()];            inputStream.read(buffer);            // 读取html内容            String htmlContent = new String(buffer,"utf-8");            inputStream.close();            // 加载到webView中            webView.loadData(htmlContent,"text/html","utf-8");        } catch (IOException e) {            e.printStackTrace();        }        // 找到界面上的按钮        Button btn = (Button)findViewById(R.id.wvBtn);        // 给按钮绑定事件        btn.setOnClickListener(new View.OnClickListener(){            @Override            public void onClick(View view) {                webView.loadUrl("javascript:show()");            }        });    }

这里写图片描述

0 0
原创粉丝点击