1. 程式人生 > >Android WebView使用全面解析(載入網路資源、本地HTML,JS互動)

Android WebView使用全面解析(載入網路資源、本地HTML,JS互動)

簡述: 

  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.     Note that, in order for your Activity to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file:
<uses-permission android:name="android.permission.INTERNET" />
  大致意思就是說WebView(網路檢視)能載入顯示網頁,可以將其視為一個瀏覽器。在使用的過程中需要加入網路許可權。瞭解了WebView我們接下來學習一下怎麼使用,本篇博文主要講解以下內容:
   ① WebView載入網路資源
   ② WebView載入本地HTML
   ③ WebView中Android呼叫JS方法
   ④ WebView中JS呼叫Android方法
   ⑤ HTML5的使用
   ⑥ JS的簡單使用

WebView載入網路資源

  載入網路資源的一般步驟如下:
     ①在XML檔案中引入WebView控制元件      ②在Activity中建立WebView例項      ③對WebView進行必要的設定(根據需要)      ④載入網路資源

    WebView簡單載入網頁

    我們按上述步驟簡單地實現載入百度首頁,首先建立XML檔案,就是簡單的在相應Activity頁面中引入WebView控制元件,如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <WebView
        android:id="@+id/local_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
    在Activity中建立WebView例項、載入網路資源比較簡單,我對程式碼做了比較詳細地註釋,直接上程式碼吧。
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private WebView webview;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = (Button) findViewById(R.id.btn);
        //建立WebView例項
        webview = (WebView) findViewById(R.id.webview);

        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (R.id.btn != v.getId())
            return;
        //跳轉到http://www.baidu.com頁面
      webview.loadUrl("http://www.baidu.com");
    }
}
    效果圖:
                                        

    改進一:不再跳轉第三方瀏覽器

        那麼這樣還是有問題,每次都要啟動第三方瀏覽器來載入網頁,我們能不能只在App內部顯示而不跳轉第三方瀏覽器呢?Google早以想到這樣的情況啦!app內部呼叫主要利用了方法setWebViewClient(),該方法裡相當於在App內部設定一個瀏覽器客戶端,該方法的引數就是一個WebViewClient例項。
        程式碼如下:
public class WebViewActivity extends Activity {

    private WebView webview_in;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web_activity);

        webview_in = (WebView) findViewById(R.id.webview_in);
        //web資源
        webview_in.loadUrl("http://www.baidu.com");
        //設定WebViewClient客戶端
        webview_in.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
    }
}
        效果圖:
                                    

    改進二:WebView開啟JavaScript功能、按返回鍵網頁後退而不是退出瀏覽器的問題

    從上面的gif動態可以看出這次並沒有跳轉到第三方瀏覽器,而是跳轉到一個Activity中(該Activity中只包含一個WebView控制元件)。但是也可以很明顯地看出該WebViewClient存在一些問題:         ①未開啟JavaScript功能 :該瀏覽器未開啟JavaScript功能(在動態圖中點選“百度知道 ”時可以看出提示);         ②按返回鍵網頁後退而不是退出瀏覽器的問題 :當我們在“百度知道 ” 頁面點選返回鍵時並沒有回到百度首頁,而是跳轉出了WebViewActivity。
            ok,我們先來解決第一個問題:為WebView開啟JavaScript功能。             核心程式碼如下:
/**
* 方法描述:啟用支援javascript
*/
private void openJavaScript() {
    WebSettings settings = webview_in.getSettings();
    settings.setJavaScriptEnabled(true);
}
       我們再來看一下第二個問題:網頁後退而不是退出瀏覽器的問題。         需要用到的API:              ①WebView.canGoBack():Gets whether this WebView has a back history item.              ②WebView.goBack(): Goes back in the history of this WebView.         解決該問題的核心程式碼:
/**
* 方法描述:改寫物理按鍵——返回的邏輯
*
* @param keyCode
* @param event
* @return
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (webview_in.canGoBack()) {
            webview_in.goBack();//返回上一頁面
            return true;
        } else {
            System.exit(0);//退出程式
        }
    }
    return super.onKeyDown(keyCode, event);
}
 現在把改進後的完整程式碼貼出來:
public class WebViewActivity extends Activity {

    private WebView webview_in;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web_activity);

        webview_in = (WebView) findViewById(R.id.webview_in);
        openJavaScript();

        //web資源
        webview_in.loadUrl("http://www.baidu.com");
        //設定WebViewClient客戶端
        webview_in.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
    }

    /**
    * 方法描述:啟用支援javascript
    */
    private void openJavaScript() {
        WebSettings settings = webview_in.getSettings();
        settings.setJavaScriptEnabled(true);
    }

    /**
    * 方法描述:改寫物理按鍵——返回的邏輯
    *
    * @param keyCode
    * @param event
    * @return
    */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webview_in.canGoBack()) {
                webview_in.goBack();//返回上一頁面
                return true;
            } else {
                System.exit(0);//退出程式
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
    解決完以上兩個問題以後我們再來看一下效果圖:
                                             

    改進三:載入進度條

    我先貼出來在模擬器中開啟瀏覽器瀏覽的情況的一張圖:    
                                                        
   
    上面這幅動態圖大家可以看出,每開啟一個網頁就會在該網頁頂端顯示一個藍色的進度條,所以我們對WebView再進一步優化:顯示進度條。      為了在WebView頂部顯示進度條我們使用ProgressBar控制元件。為了顯示進度我們需要用到的方法為setWebChromeClient (WebChromeClient client),該方法就是為了主要輔助WebView處理Javascript的對話方塊、網站圖示、網站title、載入進度等。它與WebViewClient的區別請看這篇章:WebViewClient與WebChromeClient的區別。OK,廢話不說,接下來就自定義一個WebView,程式碼來了!!!
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.webkit.WebView;
import android.widget.ProgressBar;

/**
* Created by lzy on 2016/9/22.
*/

public class ProgressWebView extends WebView {
    private ProgressBar progressbar;

    public ProgressWebView(Context context) {
        super(context);
    }

    public ProgressWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public ProgressWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initProgressBar(context);
        setWebChromeClient(new WebChromeClient());
    }

    private void initProgressBar(Context context) {
        progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, dp2px(context, 3), 0, 0));
        //改變progressbar預設進度條的顏色(深紅色)為Color.GREEN
        progressbar.setProgressDrawable(new ClipDrawable(new ColorDrawable(Color.GREEN), Gravity.LEFT, ClipDrawable.HORIZONTAL));
        addView(progressbar);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
    }

    /**
    * 方法描述:根據手機的解析度從 dp 的單位 轉成為 px(畫素)
    */
    public int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
    * 類描述:顯示WebView載入的進度情況
    */
    public class WebChromeClient extends android.webkit.WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressbar.setVisibility(GONE);
            } else {
                if (progressbar.getVisibility() == GONE)
                    progressbar.setVisibility(VISIBLE);

                progressbar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }
    }
}
        我們在佈局檔案中引入ProgressWebView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.lzy.webviewdemo.ProgressWebView
        android:id="@+id/progress_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="12dp" />
</LinearLayout>
    效果圖:
                                             

效果是不是很強勁很完美。。。。

    封裝:

    TinyWebView

     進過對上面對WebView的一步一步改進, 現在我們自定義一個WebView---TinyWebView,一個讓其支援App內部顯示資源、支援JavaScript、支援顯示進度條的WebView。OK,上程式碼:
package com.lzy.webviewdemo;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

/**
* Created by lzy on 2016/9/22.
*/

public class TinyWebView extends WebView {
    private ProgressBar progressbar;

    public TinyWebView(Context context) {
        super(context);
    }

    public TinyWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public TinyWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initProgressBar(context);
        openJavaScript();
        setWebViewClient(new WebViewClient());
        setWebChromeClient(new WebChromeClient());
    }

    private void initProgressBar(Context context) {
        progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, dp2px(context, 3), 0, 0));
        //改變progressbar預設進度條的顏色(深紅色)為Color.GREEN
        progressbar.setProgressDrawable(new ClipDrawable(new ColorDrawable(Color.GREEN), Gravity.LEFT, ClipDrawable.HORIZONTAL));
        addView(progressbar);
    }

    /**
    * 方法描述:啟用支援javascript
    */
    private void openJavaScript() {
        WebSettings settings = getSettings();
        settings.setJavaScriptEnabled(true);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
    }

    /**
    * 方法描述:根據手機的解析度從 dp 的單位 轉成為 px(畫素)
    */
    public int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
    * 類描述:顯示WebView載入的進度情況
    */
    public class WebChromeClient extends android.webkit.WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressbar.setVisibility(GONE);
            } else {
                if (progressbar.getVisibility() == GONE)
                    progressbar.setVisibility(VISIBLE);

                progressbar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }
    }
}

      WebViewActivity      

      當某個事件觸發跳轉到一個只含有WebView的Activity頁面時,我們可以封裝一個這樣的Activity。該Activity接受的引數可以自己根據情況而定,先給出一個簡單的封裝類WebViewActivity。其佈局檔案中包含一個TextView用於顯示WebView頁面的標題,還有一個WebView控制元件。比較簡單所以佈局檔案就不再貼出來了!直接看
public class WebViewActivity extends Activity {
    private TextView webviewTitle;
    private TinyWebView progressWebview;
    private String title;
    private String webViewUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.web_activity);

        getData();
        initViews();
        loadData();
    }

    /**
    * 方法描述:接收資料
    */
    private void getData() {
        webViewUrl = getIntent().getStringExtra("webview_url");
        title = getIntent().getStringExtra("webview_title");
    }

    /**
    * 方法描述:初始化WebView
    */
    private void initViews() {
        progressWebview = (TinyWebView) findViewById(R.id.progress_webview);
        webviewTitle = (TextView) findViewById(R.id.text_webView_title);
        //web資源
        progressWebview.loadUrl(webViewUrl);
    }

    /**
    * 方法描述:載入資料
    */
    private void loadData() {
        if (!TextUtils.isEmpty(title))
            webviewTitle.setText(title);

        if (TextUtils.isEmpty(webViewUrl))
            progressWebview.loadUrl(webViewUrl);
    }

    /**
    * 方法描述:改寫物理按鍵——返回的邏輯
    */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (progressWebview.canGoBack()) {
                progressWebview.goBack();//返回上一頁面
                return true;
            } else {
                System.exit(0);//退出程式
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
    * 方法描述:
    *
    * @param activity    發起跳轉的Activity
    * @param webviewUrl  WebView的url
    * @param webviewTitle WebView頁面的標題
    */
    public static void skip(Activity activity, String webviewUrl, String webviewTitle) {
        Intent intent = new Intent(activity, WebViewActivity.class);
        intent.putExtra("webview_url", webviewUrl);
        intent.putExtra("webview_title", webviewTitle);
        activity.startActivity(intent);
    }
}
        使用如下:
WebViewActivity.skip(MainActivity.this,"http://www.baidu.com","百度首頁");
       感受一下效果:
                                                

WebView載入本地HTML

    OK,關於網路資源的載入到此結束,接下來看一下本地HTML資源的載入!
    現在下來載入一個純純的本地的HTML檔案,這樣加載出來的HTML頁面不能與Android端進行通訊。載入本地HTML檔案步驟:     1、建立HTML檔案,並將其assets資料夾(當然assets資料夾也可以存放js檔案)     2、利用WebView載入本地HTML            ① 如果html檔案存於assets:則加字首:file:///android_asset/            ② 如果html檔案存於sdcard:則加字首:content://com.android.htmlfileprovider/sdcard/       注意:content字首可能導致異常,直接使用file:///sdcard/ or file:/sdcard也可以   建立一個HTML檔案        我們先建立一個HTML檔案命名為myhtmlfile.html(這裡使用的是HTML5編寫) :該檔案只顯示一段文字和一張圖片。
<!DOCTYPE html >
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <style type="text/css">
    body{ font-size:12px; line-height:24px;}
    .title{font-size:36px;
          color:#ff0000;
          text-align:center;
          margin-top:28px
        }
    .content1{font-size:24px;
              color:#ff0000;
              text-align:center;
              margin-top:18px}
  .contentothers{font-size:24px;
                  color:#ff0000;
                  text-align:center;
                  margin-top:8px}
    .imagecenter{text-align:center;
                margin-top:18px}
    </style>
</head>
<body>
<div class="imagecenter"><img src="images/haha.jpg" /></div>
<div class="title">打油詩</div>
<div class="content1">富了投機倒把的</div>
<div class="contentothers">提了吹牛拍馬的</div>
<div class="contentothers">樹了弄虛作假的</div>
<div class="contentothers">苦了奉公守法的</div>
</body>
</html>
    在Activity中載入:       重點就在這:localWebview.loadUrl("file:///android_asset/myhtmlfile.html");
public class LocalWebViewActivity extends Activity{

    private WebView localWebview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.local_webview_activity);

        localWebview = (WebView) findViewById(R.id.local_webview);
        WebSettings settings = localWebview.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);
        localWebview.loadUrl("file:///android_asset/myhtmlfile.html");
        localWebview.setWebViewClient(new WebViewClient());
    }
}
    看一下效果如何:
                                    

WebView與JS互動

    僅僅載入本地HTML比較簡單,但是這樣也不能與Android互動,顯得實用性也不是很強呀!!!那麼接下來就來講一下Android與JS的互動。
     上面的例項中我們只是簡單地展示了HTML頁面,但是HTML頁面卻不能與操控Android端的程式碼,那麼現在我們來實現以下HTML中的JS程式碼呼叫Android端的方法。

    JS呼叫Android

      1、首先要定義一個介面,這個介面相當於前端JS的服務介面(這裡指的是Android端,此時兩者的互動有點像CS結構,JS就是客戶端,Android是服務端),該介面中定義JS想要操控Android程式碼的一些方法。拿上面的案例來說,當我點選圖片時Android要彈出一個Toast,那麼在這個介面中就要為JS準備一個彈出Toast的方法。       2、要對WebView物件呼叫addJavascriptInterface()方法,這個方法就是把上一步定義的介面新增到WebView當中,意思就好像"WebView頁面中的JS客戶端可以呼叫Android端的方法了";            addJavascriptInterface()方法中有兩個引數這裡重點解釋一下,第一個引數就是我們第一步中定義的介面,那麼第一個方法為String型別,那麼它到底是什麼意思呢?它又有什麼作用呢?第二個引數就是我們第一個引數的“替身”,為什麼需要替身呢?JS呼叫Android程式碼的時候,在前端JS程式碼中不可能直接呼叫“介面名稱 .XXX()”,所以這時候就用到替身了。那麼JS中呼叫Android程式碼(更準確地說是呼叫我們定義的介面)就可以“替身.XXX()”。       說了這麼多現在趕緊實現一下。我們得實現在上述例子的基礎上給圖片新增一個點選事件,當用戶點選圖片的時候JS呼叫Android介面中的方法彈出一個Toast。       我先把前端HTML頁面展示出來,其實就是在上述的基礎上給圖片添加了一個“onClick()”事件。
<!DOCTYPE html >
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <style type="text/css">
    body{ font-size:12px; line-height:24px;}
    .title{font-size:36px;
          color:#ff0000;
          text-align:center;
          margin-top:28px
        }
    .content1{font-size:24px;
              color:#ff0000;
              text-align:center;
              margin-top:18px}
  .contentothers{font-size:24px;
                  color:#ff0000;
                  text-align:center;
                  margin-top:8px}
    .imagecenter{text-align:center;
                margin-top:18px}

    </style>
    <script type="text/javascript">
    function invokeAndroidMethod(info) {
      javascript:<span style="font-size:18px;"><strong><span style="color:#FF0000;">qwert</span></strong></span>.showToast(info);
    }

    </script>
</head>
<body>
<div class="imagecenter"><img id="image" src="images/haha.jpg"
                              onclick="invokeAndroidMethod('JS呼叫Android中的方法!')"/></div>
<div class="title">打油詩</div>
<div class="content1">富了投機倒把的</div>
<div class="contentothers">提了吹牛拍馬的</div>
<div class="contentothers">樹了弄虛作假的</div>
<div class="contentothers">苦了奉公守法的</div>
</body>
</html>
          這裡要提醒一下,紅色的“qwert”就是我們剛才說的“替身”,這個替身可以隨意命名,但是注意要與addJavascriptInterface()中的第二個引數一致。
    我們接下里再來看看Android端程式碼:
public class LocalWebViewActivity extends Activity{

    private WebView localWebview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.local_webview_activity);

        localWebview = (WebView) findViewById(R.id.local_webview);
        WebSettings settings = localWebview.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);
        //WebView新增JS要呼叫的介面,注意引數
       <span style="color:#FF0000;"> localWebview.addJavascriptInterface(new JsInterface(),"<span style="font-size:18px;"><strong>qwert</strong></span>");</span>
        localWebview.loadUrl("file:///android_asset/myhtmlfile.html");
        localWebview.setWebViewClient(new WebViewClient());
    }

  <span style="color:#FF0000;">  /**
    * 介面描述:供JS呼叫的介面
    */
    public class JsInterface{
        /**
        *  方法描述:彈出一個Toast
        * @param message JS端需要傳遞的引數(也就是要Toast的內容)
        */
        @JavascriptInterface
        public void showToast(String message) {
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
        }
    }</span>
}
    與上一個案例中的程式碼變化的地方用紅色標記了。現在看一下效果:
                                      
    JS呼叫Android中的方法現在已經實現,那麼我們接下來看看Android呼叫JS的方法,Android代用JS可比JS呼叫Android簡單多了哦!!!

    Android呼叫JS

    步驟:       1、載入HTML:
webview.loadUrl("file:///android_asset/myhtmlfile.html");
      2、設定JavaScript可用
WebSettings settings = localWebview.getSettings();
settings.setJavaScriptEnabled(true);
      3、呼叫HTML中用到的JavaScript方法        通過webView.loadUrl("javascript:xxx")方式就可以呼叫當前網頁中的名稱為xxx的javascript方法,如下:
webView.loadUrl("javascript:changeTitle('Android呼叫JS操控HTML介面')");
    例項:     我們在之前的HTML頁面中再新增一個JS方法,讓這個方法改變打油詩的標題,調整後的HTML程式碼如下:
<!DOCTYPE html >
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <style type="text/css">
    body{ font-size:12px; line-height:24px;}
    .title{font-size:36px;
          color:#ff0000;
          text-align:center;
          word-wrap:break-word;
          word-break:break-all;
          margin: 0 auto;
          line-height:150%;
          margin-top:28px
        }
    .content1{font-size:24px;
              color:#ff0000;
              text-align:center;
              margin-top:18px}
  .contentothers{font-size:24px;
                  color:#ff0000;
                  text-align:center;
                  margin-top:8px}
    .imagecenter{text-align:center;
                margin-top:18px}

    </style>
    <script type="text/javascript">
    function invokeAndroidMethod(info) {
      javascript:qwert.showToast(info);
    }
   <span style="color:#FF0000;"> <strong>function changeTitle(title) {
        document.getElementById('title').innerHTML= title;
    }</strong>
</span>
    </script>
</head>
<body>
<div class="imagecenter"><img style="border:1px #FF0000 solid;"id="image" src="images/haha.jpg" border="2"
                              onclick="invokeAndroidMethod('JS呼叫Android中的方法!')"/></div>
<div class="title" id="title">打油詩</div>
<div class="content1">富了投機倒把的</div>
<div class="contentothers">提了吹牛拍馬的</div>
<div class="contentothers">樹了弄虛作假的</div>
<div class="contentothers">苦了奉公守法的</div>
</body>
</html>
    為了更能簡單地說明問題,我們再建一個Activity類,由於比較簡單直接上程式碼:
/**
* 類描述:Android呼叫JS
* Created by lzy on 2016/9/22.
*/
public class AndroidInvokeJS extends Activity {

    private Button btn_android_invoke_js;
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.android_invoke_js);
        btn_android_invoke_js = (Button) findViewById(R.id.btn_android_invoke_js);

        webView = (WebView) findViewById(R.id.wv_android_invoke_js);
        // ①載入HTML檔案
        webView.loadUrl("file:///android_asset/myhtmlfile.html");
        // ②設定JavaScript可用
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        btn_android_invoke_js.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // ③呼叫HTML中用到的JavaScript方法
                webView.loadUrl("javascript:changeTitle('Android呼叫JS操控HTML介面')");
            }
        });

    }
}
    效果圖:
                                          
現在既實現了Android呼叫JS又現在了JS呼叫Android,那麼將兩者結合一下即可實現Android與JS的相互呼叫哦!!!

將程式碼整理後的下載連結:原始碼下載