需求描述

在使用 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.

翻译一下,三种情况:

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

因此,开篇的需求使用如下方法即可实现:

设置 WebViewClient 且在其 shouldOverrideUrlLoading 方法返回 false

示例程序见 WebViewClientTest

最新文章

  1. 转载文章-----Rational Rose2007(v7.0)下载地址、安装及激活详解教程(图)
  2. 基础小功能之(1)震动,(2)检测app是否在前台运行
  3. poj1160 post office
  4. Windows下Subversion和Apache的安装及配置(一)
  5. JS实现文本复制与剪切
  6. 【Struts2学习笔记(11)】对action的输入校验和XML配置方式实现对action的全部方法进行输入校验
  7. C++ Socket学习记录 -2
  8. lua continue实现
  9. iframe 里的高度自适应
  10. js黑魔法
  11. redis安装相关下载
  12. 火币网API文档——WebSocket API Reference
  13. ipfs docker 运行试用
  14. Ros系列_学习一
  15. RESET MASTER和RESET SLAVE使用场景和说明【转】
  16. [flask]flask_login模块,session及其他
  17. keytool命令总结
  18. day 15
  19. jbd2/dm-2-8 io太高
  20. Throwable类

热门文章

  1. 洛谷 P1012 拼数 Label:续命模拟QAQ
  2. 去掉inline-block元素默认间距的几种方法
  3. Linux中安装jdk
  4. C# PInvoke(DllImport使用) 进阶教程(一)转
  5. VS重新生成后仍然执行旧代码
  6. Setting start page of Windows Phone dynamically through code
  7. [转]B树、B-树、B+树、B*树
  8. [LintCode] Flatten Nested List Iterator 压平嵌套链表迭代器
  9. android-ProgressBar
  10. webform连接ACCESS数据库