Android WebWiew 使用詳解

WebView 從字面意思上來看,第一他是個Web,第二他是個View。
那麼Web的工作就是加載網絡資源。
View就是Android的控件,在容器中進行內容的顯示。
合起來就是加載網絡資源,在Android中進行顯示。

那麼加載網絡資源最重要的就是loadUrl 即加載的地址。
那麼最核心的方法就是:

public void loadUrl(String url) {}

但是和加載圖片一樣,加載數據就涉及到對加載選項的配置,比如說緩存信息的設置等等。
那麼爲了讓WebView更好的工作,我們就需要了解具體有那些配置項,將配置項設置好,就可以讓他更好的進行工作。

接下來我們從Layout開始講解一下,從定義到使用,我們要進行那些工作,和這些工作都是幹什麼的。

第一步在Layout中進行聲明;

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

非常簡單,只需三行,其他的在程序內部搞定!

第二步得到我們的VebView對象

webView = (WebView) findViewById(R.id.webview);

第三步就是大家最關心的調用加載網絡數據

webView.loadUrl("http://www.baidu.com");

但是如果直接使用此方法,會調用系統默認的瀏覽器進行數據加載。(其實我們是需要在我們的容器裏進行數據的顯示而不是打開瀏覽器。因爲大多數時候是使用這個控件顯示一些商品的信息,打開瀏覽器的體驗並不是很好!)

那麼如何實現那,WebView易已經想好了,那麼我就使用這個方法。

myWeb.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                    String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                myWeb.loadUrl("file:///android_asset/err.html");
        myWeb.setVisibility(View.GONE);     
            }
        });

注:loadurl(url)依然需要使用。
shouldOverrideUrlLoading()
一般情況下我們不需要重寫,這個函數有一個返回值,當爲false時的意思使我們不用管, 當前的webView正在加載這個Url。當返回true就讓我們自己操作。

/**
 * 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.
 */

onReceivedError()
當接收的網絡信息錯誤時,就會調用這個方法。那麼我們需要指向一個備用站,或者將這個WebView進行隱藏。

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}.
 */

翻譯過來就是,當你的網頁被加載完成時,被渲染的圖片(緩衝)可能還沒有加載好,需要進一步對WebView的PictureListener pic方法進行再次監聽,已實現完全加載完成時,進行操作。

/**
 * 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) {
}

這個函數是這要加載資源就會被調用。
我們可以自定義一個小動畫,在裏面,避免空白頁帶來的尷尬。

/**
 * 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) {}

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

說道了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); //支持自動加載圖片

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章