Android中webView的基礎使用(一)

WebView是View的一個子類,可讓你在activity中顯示網頁。

能夠在佈局文件中寫入WebView:好比下面這個寫了一個填滿整個屏幕的WebView:html

1 <?xml version="1.0" encoding="utf-8"?>
2 <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
3     android:id="@+id/webview"
4     android:layout_width="fill_parent"
5     android:layout_height="fill_parent"
6 />

加載一個網頁,使用loadUrl()java

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl(http://www.example.com);  

注意要在manifest中加上訪問網絡的權限:android

 

<manifest ... > 
    <uses-permission android:name="android.permission.INTERNET" /> 
    ... 
</manifest>

設置WebView要顯示的網頁

設置WevView要顯示的網頁方法有不少:web

互聯網頁面直接用:瀏覽器

myWebView.loadUrl(「http://www.google.com「);

本地文件用:網絡

myWebView.loadUrl(「file:///android_asset/XX.html「); 

本地文件存放在:assets文件中。app

還能夠直接載入html的字符串,如:webapp

String htmlString = "<h1>Title</h1><p>This is HTML text<br /><i>Formatted in italics</i><br />Anothor Line</p>";
// 載入這個html頁面
myWebView.loadData(htmlString, "text/html", "utf-8");

在WebView中使用JavaScript

若是你想要載入的頁面中用了JavaScript,你必須爲你的WebView使能JavaScript。ide

一旦使能以後,你也能夠本身建立接口在你的應用和JavaScript代碼間進行交互。佈局

使能JavaScript能夠經過getSettings()得到WebSettings,而後用setJavaScriptEnabled()使能JavaScript:

WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

WebSettings中提供了不少有用的設置。

處理頁面瀏覽

  當用戶點擊了你的WebView中的一個連接,默認的行爲是Android啓動一個處理URL的應用,一般,默認的瀏覽器打開並下載目標URL。

  可是,你能夠在你的WebView中覆蓋這一行爲,使得鏈接仍在你的WebView中打開。

  以後,根據在WebView中維護的網頁瀏覽歷史,你能夠容許用戶向前或向後瀏覽他們的網頁。

在WebView中打開全部連接

要打開用戶點擊的連接,只須要用setWebViewClient()方法向你的WebView提供一個WebViewClient 好比:

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());

此時就OK了, 就能夠在你的WebView中打開連接了。

關於打開連接位置的更多控制

若是你對在哪裏打開連接須要更多的控制,你能夠建立本身的類,繼承 WebViewClient,而後覆寫shouldOverrideUrlLoading() 方法。

好比下面這個:

 1 private class MyWebViewClient extends WebViewClient
 2     {
 3         @Override
 4         public boolean shouldOverrideUrlLoading(WebView view, String url)
 5         {
 6 
 7        if(Uri.parse(url).getHost().equals(www.example.com))
 8             {
 9                 // This is my web site, so do not override; let my WebView load
10                 // the page
11                 return false;
12             }
13             // Otherwise, the link is not for a page on my site, so launch
14             // another Activity that handles URLs
15             Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
16             startActivity(intent);
17             return true;
18         }
19     }

將特定的連接用本身的WebView打開,其餘連接用瀏覽器(intent啓動了默認的處理URL的Activity)。

定義完以後把這個類的對象傳入setWebViewClient()方法便可。

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new MyWebViewClient());

實踐驗證:在直接設置setWebViewClient(new WebViewClient());時驗證正確,即全部連接都是在WebView中打開。

  在設置爲自定義的WebViewClient子類對象時,發現連接仍然都是從默認瀏覽器中打開。

瀏覽網頁歷史回退

  當你的WebView覆寫了URL載入的行爲,它會自動地對訪問過的網頁積累一個歷史,你能夠利用 goBack() 和 goForward()方法在這個歷史中前進或後退。

  好比說使用後退鍵進行網頁後退:

 1 /**
 2      * 按鍵響應,在WebView中查看網頁時,按返回鍵的時候按瀏覽歷史退回,若是不作此項處理則整個WebView返回退出
 3      */
 4     @Override
 5     public boolean onKeyDown(int keyCode, KeyEvent event)
 6     {
 7         // Check if the key event was the Back button and if there's history
 8         if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack())
 9         {
10             // 返回鍵退回
11             myWebView.goBack();
12             return true;
13         }
14         // If it wasn't the Back key or there's no web page history, bubble up
15         // to the default
16         // system behavior (probably exit the activity)
17         return super.onKeyDown(keyCode, event);
18     }

 canGoBack() 方法在網頁能夠後退時返回true。

  相似的,canGoForward()方法能夠檢查是否有能夠前進的歷史記錄。

  若是你不執行這種檢查,一旦 goBack() 和 goForward()方法到達歷史記錄頂端,它們將什麼也不作。

  若是不加這種設置,在用戶按下Back鍵時,若是是WebView顯示網頁,則會將WebView做爲總體返回。

程序實例

  附上完整的程序:

  1 WebView Basic
  2 
  3 import android.annotation.SuppressLint;
  4 import android.app.Activity;
  5 import android.content.Intent;
  6 import android.net.Uri;
  7 import android.os.Bundle;
  8 import android.view.KeyEvent;
  9 import android.view.Menu;
 10 import android.webkit.WebSettings;
 11 import android.webkit.WebView;
 12 import android.webkit.WebViewClient;
 13 
 14 @SuppressLint("SetJavaScriptEnabled")
 15 public class WebActivity extends Activity
 16 {
 17     private WebView myWebView = null;
 18 
 19     @Override
 20     public void onCreate(Bundle savedInstanceState)
 21     {
 22         super.onCreate(savedInstanceState);
 23         setContentView(R.layout.activity_web);
 24 
 25         // 打開網頁
 26         myWebView = (WebView) findViewById(R.id.webview);
 27         //
 28 
 29         // myWebView.loadUrl("http://www.cnblogs.com/mengdd/");// 博客連接
 30         myWebView.loadUrl("http://www.baidu.com/");// 百度連接
 31 
 32         // JavaScript使能(若是要加載的頁面中有JS代碼,則必須使能JS)
 33         WebSettings webSettings = myWebView.getSettings();
 34         webSettings.setJavaScriptEnabled(true);
 35 
 36         // 在WebView中打開連接(默認行爲是使用瀏覽器,設置此項後都用WebView打開)
 37         // myWebView.setWebViewClient(new WebViewClient());
 38         // 這樣設置後全部的連接都會在當前WebView中打開
 39 
 40         // 更強的打開連接控制:本身覆寫一個WebViewClient類:除了指定連接從WebView打開,其餘的連接默認打開
 41         myWebView.setWebViewClient(new MyWebViewClient());
 42 
 43     }
 44 
 45     @Override
 46     public boolean onCreateOptionsMenu(Menu menu)
 47     {
 48         getMenuInflater().inflate(R.menu.activity_web, menu);
 49         return true;
 50     }
 51 
 52     /**
 53      * 自定義的WebViewClient類,將特殊連接從WebView打開,其餘連接仍然用默認瀏覽器打開
 54      * 
 55      * @author 1
 56      * 
 57      */
 58     private class MyWebViewClient extends WebViewClient
 59     {
 60         @Override
 61         public boolean shouldOverrideUrlLoading(WebView view, String url)
 62         {
 63             if (Uri.parse(url)
 64                     .getHost()
 65                     .equals("http://www.cnblogs.com/mengdd/archive/2013/02/27/2935811.html")
 66                     || Uri.parse(url).getHost()
 67                             .equals("http://music.baidu.com/"))
 68             {
 69                 // This is my web site, so do not override; let my WebView load
 70                 // the page
 71 
 72                 // 這是官網上的例子,可是我點擊特定連接的時候仍然是用瀏覽器而不是用本身的WebView打開,加上下面這句view.loadUrl(url)仍然是用瀏覽器,無解,不知道哪裏出了問題
 73                 // view.loadUrl(url);
 74                 return false;
 75             }
 76             // Otherwise, the link is not for a page on my site, so launch
 77             // another Activity that handles URLs
 78             Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
 79             startActivity(intent);
 80             return true;
 81         }
 82     }
 83 
 84     /**
 85      * 按鍵響應,在WebView中查看網頁時,按返回鍵的時候按瀏覽歷史退回,若是不作此項處理則整個WebView返回退出
 86      */
 87     @Override
 88     public boolean onKeyDown(int keyCode, KeyEvent event)
 89     {
 90         // Check if the key event was the Back button and if there's history
 91         if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack())
 92         {
 93             // 返回鍵退回
 94             myWebView.goBack();
 95             return true;
 96         }
 97         // If it wasn't the Back key or there's no web page history, bubble up
 98         // to the default
 99         // system behavior (probably exit the activity)
100         return super.onKeyDown(keyCode, event);
101     }
102 
103 }

參考資料

  關於Web方面推薦的一個學習網站:

  http://www.w3school.com.cn/

  API Guides:  Building Web Apps in WebView

  http://developer.android.com/guide/webapps/webview.html

  其餘學習連接:

  http://www.cnblogs.com/aimeng/archive/2012/05/24/2516547.html

  http://www.apkbus.com/android-44567-1-1.html

相關文章
相關標籤/搜索