編輯:Android 資訊
關於 WebView 的基礎用法在此不多贅述,載入網頁的核心方法就是:
public void loadUrl(String url) {}
接下來,本文將圍繞 WebView 介紹一系列實用配置。
首先,如果你寫下這樣的程式碼:
webView = (WebView) findViewById(R.id.webview); webView.loadUrl("https://www.baidu.com");
你會發現應用自動呼叫了手機系統的預設瀏覽器。此時,只要加上這一行即可避免:
webView.setWebViewClient(new WebViewClient()}
再次運行後,就不會再跳出預設瀏覽器了。下面為大家介紹 WebViewClient 這個類。它在日常開發中被大量使用,先看幾個核心方法:
public boolean shouldOverrideUrlLoading(WebView view, String url) { return false; }
一般情況下無須重寫。這個方法有個回傳值:回傳 false 表示交給當前 WebView 自行載入該網址;回傳 true 則表示由我們自行處理。
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) { }
重寫這個方法能讓你的應用更加人性化。
接著又有個需求:我們希望顯示載入進度條。這時就該用到 WebChromeClient 類,而非 WebViewClient:
/** * 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) {}
一個用來取得網頁標題,另一個則用來取得標題旁的圖示。
再來談談 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;//此值已過時,無須理會 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); }
如此便能完美解決。
最後,一起來看看 WebSettings 的其他常用設定:
setJavaScriptEnabled(true); //支持js setPluginsEnabled(true); //支持插件 setUseWideViewPort(false); //將圖片調整到適合webview的大小 setSupportZoom(true); //支持縮放 setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); //支持內容重新布局 supportMultipleWindows(); //多窗口 setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //設置緩存模式 setAllowFileAccess(true); //設置可以訪問文件 setNeedInitialFocus(true); //當webview調用requestFocus時為webview設置節點 webview webSettings.setBuiltInZoomControls(true); //設置支持縮放 setJavaScriptCanOpenWindowsAutomatically(true); //支持通過JS打開新窗口 setLoadWithOverviewMode(true); // 縮放至屏幕的大小 setLoadsImagesAutomatically(true); //支持自動加載圖片
歡迎大家補充與指正。
Android UI 元件系列:WebView 網路檢視
Android 的網路功能十分強大,WebView 元件能直接載入網頁,可將其視為一個內建的瀏覽器。要實現這個功能,具體步驟如下: 1、在版面配置檔中宣告 WebView
Activity 生命週期與四種啟動模式完整整理
先看生命週期全圖 按鍵如何影響生命週期 BACK 鍵:按下 BACK 代表結束目前 App,依序觸發 onPause() → onStop() → onDestroy
23 種設計模式在 Android 專案中的落地與重構實踐
前言 本文結合實際專案談 23 種設計模式,每個模式都從四個角度切入: (1) 定義:抽象定義加上通俗描述,講清楚它解決什麼問題、適用什麼場景(2) 示例:專案中若用過就
Android Activity 全面解析:生命週期、啟動模式、Intent 匹配與轉場動畫
Activity 是 Android 四大元件之一,也是使用者最直接感受到的頁面容器。要真正掌握 Activity,不能只看 onCreate 與 setContentV