Android之WebView中的WebViewClient设置与否

    在使用 WebView 的项目中,一个常见的需求是将页面内的链接跳转限制在 WebView 内,而不是使用外部浏览器打开,但 WebView 的默认行为是将链接点击事件作为 Intent 发送给系统,由系统决定如何处理(通常的行为是使用浏览器打开或是弹出浏览器选择对话框);但有时又会有需求使用webview但仍然调用系统浏览器打开页面。网上多数资料认为重新设置WebViewClient,重写里面的shouldOverrideUrlLoading方法且将其返回值改为true则不调用系统或其他浏览器打开页面,false则会调用系统浏览器。个人验证这种说法既简陋又错误!

    (以下内容参考自https://www.cnblogs.com/shaobin0604/p/3313680.html)

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.

翻译一下,三种情况:

  1. 若没有设置 WebViewClient 则在点击链接之后由系统处理该 url,通常是使用浏览器打开或弹出浏览器选择对话框。
  2. 若设置 WebViewClient 且该方法返回 true ,则说明由应用的代码处理该 url,WebView 不处理。
  3. 若设置 WebViewClient 且该方法返回 false,则说明由 WebView 处理该 url,即用 WebView 加载该 url。

    即:只要设置了WebViewClient 无论是否重写其shouldOverrideUrlLaoding方法,也不管返回true还是false都不会再调用系统浏览器去打开网页,而是都直接在webview中打开网页!

另,设置WebChromeClient不会影响对系统浏览器的调用,可以在这里面重置一些功能以实现更好的展示效果。

猜你喜欢

转载自blog.csdn.net/weixin_40571358/article/details/80554376