需求描述
在使用 WebView
的項目中,一個常見的需求是將頁面內的鏈接跳轉限制在 WebView
內,而不是使用外部瀏覽器打開,但 WebView
的默認行為是將鏈接點擊事件作為 Intent
發送給系統,由系統決定如何處理(通常的行為是使用瀏覽器打開或是彈出瀏覽器選擇對話框),那么如何實現期望的效果呢?
實現方案
文章關於用WebView或手機瀏覽器打開連接問題給出了一種使用 WebViewClient#shouldOverrideUrlLoading
方法的方案可以達到效果,但其使用該方法的方式是錯誤的,且被廣泛傳播。因此,有必要在此澄清一下。
WebView#shouldOverrideUrlLoading
的 api doc 如下
public boolean shouldOverrideUrlLoading (WebView view, String url) Added in API level 1
Give the host application a chance to take over the control when a > new url is about to be loaded in the current WebView.
If WebViewClient is not provided, by default WebView will ask Activity Manager to choose the proper handler for the url.
If WebViewClient is provided, return true means the host application handles the url, while return false means the current WebView handles the url. This method is not called for requests using the POST "method".
Parameters view The WebView that is initiating the callback. url The url to be loaded.
Returns True if the host application wants to leave the current WebView and handle the url itself, otherwise return false.
翻譯一下,三種情況:
- 若沒有設置
WebViewClient
則在點擊鏈接之后由系統處理該 url,通常是使用瀏覽器打開或彈出瀏覽器選擇對話框。 - 若設置
WebViewClient
且該方法返回 true ,則說明由應用的代碼處理該 url,WebView
不處理。 - 若設置
WebViewClient
且該方法返回 false,則說明由WebView
處理該 url,即用WebView
加載該 url。
因此,開篇的需求使用如下方法即可實現:
設置
WebViewClient
且在其shouldOverrideUrlLoading
方法返回 false
示例程序見 WebViewClientTest