Android之WebView中的WebViewClient设置与否

本文详细解析了WebView中shouldOverrideUrlLoading方法的作用机制。通过对比不同返回值的影响,阐述了如何控制WebView内链接的打开方式,避免误用导致的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    在使用 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不会影响对系统浏览器的调用,可以在这里面重置一些功能以实现更好的展示效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值