Android中WebView使用解析

gefufeng發表於2016-02-20

對於webview的簡單使用在這裡不做過多的說明,使用webview載入網頁的核心方法是

public void loadUrl(String url) {}

下面就是介紹圍繞webview進行的一系列的配置。

首先如果你呼叫了下面程式碼:

webView = (WebView) findViewById(R.id.webview);
webView.loadUrl("http://www.baidu.com");

你會發現你的app會自動開啟手機系統自帶的預設瀏覽器,這時候我們需要加一行:

webView.setWebViewClient(new WebViewClient()}

然後再執行發現就不呼叫預設瀏覽器了,下面為大家講講WebViewClient這個類:WebViewClient類中的幾個方法在我們平時開發中大量的運用,首先是

public boolean shouldOverrideUrlLoading(WebView view, String url) {
    return false;
}

一般情況下我們不需要重寫,這個函式有一個返回值,當為false時意思是我們不用管,當前的webview自已載入這個url,當返回為ture時,就讓我們自己操作。

public void onPageFinished(WebView view, String url) {
}

當頁面載入完成時呼叫,但需要注意的是

/**
 * When onPageFinished() is called, the
 * rendering picture may not be updated yet. To get the notification for the
 * new Picture, use {@link WebView.PictureListener#onNewPicture}.
 */

也就是渲染圖片有可能沒有載入完成。

/**
 * Notify the host application that the WebView will load the resource
 * specified by the given url.
 *
 * @param view The WebView that is initiating the callback.
 * @param url The url of the resource the WebView will load.
 */
public void onLoadResource(WebView view, String url) {
}

這個函式是這要載入資源就會被呼叫。然後說一下錯誤處理的函式:

/**
 * Report an error to the host application. These errors are unrecoverable
 * (i.e. the main resource is unavailable). The errorCode parameter
 * corresponds to one of the ERROR_* constants.
 * @param view The WebView that is initiating the callback.
 * @param errorCode The error code corresponding to an ERROR_* value.
 * @param description A String describing the error.
 * @param failingUrl The url that failed to load.
 * @deprecated Use {@link #onReceivedError(WebView, WebResourceRequest, WebResourceError)
 *             onReceivedError(WebView, WebResourceRequest, WebResourceError)} instead.
 */
@Deprecated
public void onReceivedError(WebView view, int errorCode,
        String description, String failingUrl) {
}

重寫該函式讓你的app更加人性化。

那這裡我們又有一個需求:我們要有一個進度條,那我們怎麼知道時時的載入進度呢,就不是在WebViewClient類中了,而是在WebChromeClient中:

/**
 * Tell the host application the current progress of loading a page.
 * @param view The WebView that initiated the callback.
 * @param newProgress Current page loading progress, represented by
 *                    an integer between 0 and 100.
 */
public void onProgressChanged(WebView view, int newProgress) {}

其中引數newProgress就是載入的時時進度。WebChromeClient中還用一些常用的函式,比如:

/**
 * Notify the host application of a change in the document title.
 * @param view The WebView that initiated the callback.
 * @param title A String containing the new title of the document.
 */
public void onReceivedTitle(WebView view, String title) {}

/**
 * Notify the host application of a new favicon for the current page.
 * @param view The WebView that initiated the callback.
 * @param icon A Bitmap containing the favicon for the current page.
 */
public void onReceivedIcon(WebView view, Bitmap icon) {}

一個是可以獲取網頁的title,一個是可以title旁邊的icon。

然後說一下webview快取問題:有時候我們有快取的需求,就是在沒有網路的情況下,以前可以開啟的網頁也可以通過快取檔案開啟,主要程式碼為:

webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webSettings.setAppCacheEnabled(true);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/gefdemoweb";
Log.e(null,path);
webSettings.setAppCachePath(path);

第一行設定了快取模式,第二行設定可以快取,然後下面設定快取路徑,關於快取模式有很多種:

public static final int LOAD_DEFAULT = -1;//預設模式,當快取資源是可用的不過期,就使用,否次網路載入
public static final int LOAD_NORMAL = 0;//This value is obsolete,過時了,不用管
public static final int LOAD_CACHE_ELSE_NETWORK = 1;//當快取資源是可用的就使用,即使它是過期的,否次網路載入
public static final int LOAD_NO_CACHE = 2;//不使用快取
public static final int LOAD_CACHE_ONLY = 3;//不使用網路

然後說一下按返回鍵的問題,如果你不做任何設定,按返回鍵肯定要跳到上一個activity,但是我們想讓他返回到上一個載入的網頁怎麼辦:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){
        webView.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

完美解決。

最後看一下webSetting的其它常用設定:

setJavaScriptEnabled(true);  //支援js
setPluginsEnabled(true);  //支援外掛 
setUseWideViewPort(false);  //將圖片調整到適合webview的大小 
setSupportZoom(true);  //支援縮放 
setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); //支援內容重新佈局  
supportMultipleWindows();  //多視窗 
setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  //關閉webview中快取 
setAllowFileAccess(true);  //設定可以訪問檔案 
setNeedInitialFocus(true); //當webview呼叫requestFocus時為webview設定節點
webview webSettings.setBuiltInZoomControls(true); //設定支援縮放 
setJavaScriptCanOpenWindowsAutomatically(true); //支援通過JS開啟新視窗 
setLoadWithOverviewMode(true); // 縮放至螢幕的大小
setLoadsImagesAutomatically(true);  //支援自動載入圖片

歡迎補充和糾正

相關文章