【Android开发学习笔记】关于WebView自我调用链接的问题

之前一直很疑惑,看了很多webview控件的简单实例,发现打开网页是正常的,但是单击链接的时候,会自动调用android自带的浏览器来打开链接,苦苦搜寻后终于找到问题所在

参考《Android Developers》,感谢

  1. You now have a simplest web page viewer. It’s not quite a browser yet because as soon as you click a link, the default Android Browser handles the Intent to view a web page, because this Activity isn’t technically enabled to do so. Instead of adding an intent filter to view web pages, you can override the WebViewClient class and enable thisActivity to handle its own URL requests.

  2. In the HelloAndroid Activity, add this nested class:
    private class HelloWebViewClient extends WebViewClient {
       
    @Override
       
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view
    .loadUrl(url);
           
    return true;
       
    }
    }
  3. Then towards the end of the onCreate(Bundle) method, set an instance of the HelloWebViewClient as the WebViewClient:
    mWebView.setWebViewClient(new HelloWebViewClient());

关于shouldOverrideUrlLoading,见下

public boolean shouldOverrideUrlLoading (WebView view, String url)

Since: 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.

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.

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注