android中webview控制項和javascript互動執行個體_Android

來源:互聯網
上載者:User

當我們要實現豐富的圖文混排效果的時候,我們一般會使用webview,這是一個功能十分強大的的控制項,來看看官方的解釋:

複製代碼 代碼如下:
A View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more.

一個能顯示網頁內容的View。該類是你實現一個自己的瀏覽器,或者只是在activity中顯示網頁內容的基礎;它基於WebKit核心來顯示網頁,並且包含了實現前後翻頁、放大縮小,文字搜尋方法。

從上面你應該瞭解到了準系統,也就是顯示網頁。這篇文章中我們主要討論webview和Javascript的互動。如果你的js基礎比java基礎好的話那麼採用這種方式做一些複雜的處理是個不錯的選擇。

WebView和js的互動包含兩方面,一是在html中通過js調用安卓的java代碼;二是在安卓java代碼中調用js。

一、html中通過js調用java代碼

js中調用java代碼其實就記住一點,webview設定一個和js互動的介面(注意這裡只是一般的意思,並不是java中介面的含義),這個介面其實是一個一般的類,同時為這個介面取一個別名。這個過程如下:

複製代碼 代碼如下:

mWebView.addJavascriptInterface(new DemoJavaScriptInterface(),"demo");

new  DemoJavaScriptInterface就是這個介面,demo就是這個介面的別名。
上面的代碼執行之後在html的js中就能通過別名(這裡是“demo”)來調用newDemoJavaScriptInterface類中的任何方法。

如我們想讓html中的一個button點擊之後調用java中的函數可以這樣:

複製代碼 代碼如下:

<input type="button"  value="click me"  onclick="window.demo.clickOnAndroid()"/>

但是因為安全問題,在Android4.2中(如果應用的android:targetSdkVersion數值為17+)JS只能訪問帶有 @JavascriptInterface註解的Java函數。因此如果你的開發版本比較高,需要在被調用的函數前加上@JavascriptInterface註解。

下面是Google給出的程式碼範例:
WebViewDemo.java

複製代碼 代碼如下:

package com.google.android.webviewdemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
/**
 * Demonstrates how to embed a WebView in your activity. Also demonstrates how
 * to have javascript in the WebView call into the activity, and how the activity
 * can invoke javascript.
 * <p>
 * In this example, clicking on the android in the WebView will result in a call into
 * the activities code in {@link DemoJavaScriptInterface#clickOnAndroid()}. This code
 * will turn around and invoke javascript using the {@link WebView#loadUrl(String)}
 * method.
 * <p>
 * Obviously all of this could have been accomplished without calling into the activity
 * and then back into javascript, but this code is intended to show how to set up the
 * code paths for this sort of communication.
 *
 */
public class WebViewDemo extends Activity {
    private static final String LOG_TAG = "WebViewDemo";
    private WebView mWebView;
    private Handler mHandler = new Handler();
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        mWebView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(false);
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");
        mWebView.loadUrl("file:///android_asset/demo.html");
    }
    final class DemoJavaScriptInterface {
        DemoJavaScriptInterface() {
        }
        /**
         * This is not called on the UI thread. Post a runnable to invoke
         * loadUrl on the UI thread.
         */
        public void clickOnAndroid() {
            mHandler.post(new Runnable() {
                public void run() {
                    mWebView.loadUrl("javascript:wave()");
                }
            });
        }
    }
    /**
     * Provides a hook for calling "alert" from javascript. Useful for
     * debugging your javascript.
     */
    final class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.d(LOG_TAG, message);
            result.confirm();
            return true;
        }
    }
}

demo.html

複製代碼 代碼如下:

<html>
    <script language="javascript">
        /* This function is invoked by the activity */
        function wave() {
            alert("1");
            document.getElementById("droid").src="android_waving.png";
            alert("2");
        }
    </script>
    <body>
        <!-- Calls into the javascript interface for the activity -->
        <a onClick="window.demo.clickOnAndroid()"><div style="width:80px;
            margin:0px auto;
            padding:10px;
            text-align:center;
            border:2px solid #202020;" >
                <img id="droid" src="android_normal.png"/><br>
                Click me!
        </div></a>
    </body>
</html>

main.xml

複製代碼 代碼如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >                                            
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/intro"
        android:padding="4dip"
        android:textSize="16sp"
        />
    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        />
</LinearLayout>

二、android調用js

上面的代碼在示範如何在js中調用java代碼的同時也示範了如何在java中調用js
調用形式:

複製代碼 代碼如下:
mWebView.loadUrl("javascript:wave()");

其中wave()是js中的一個方法,當然你可以把這個方法改成其他的方法,也就是android調用其他的方法。

demo的解釋:

現在你一定瞭解了android和js的互動了。是時候分析一些demo了,根據上面講的你也應該比較清楚了。具體互動流程如下:

①點擊圖片,則在js端直接調用android上的方法clickOnAndroid();
②clickOnAndroid()方法(利用線程)調用js的方法。
③被②調用的js直接控制html。

個人總結:利用webView的這種方式在有些時候UI布局就可以轉成相應的html代碼編寫了,而html配置樣式之類有DW這樣強大的工具,而且網上很多源碼,很多代碼片。在UI和視覺效果上就會節省很多時間,重複發明輪子沒有任何意義。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.