对WebView中WebViewClient类shouldOverrideUrlLoading方法的理解

相信各位看官也是不少使用 WebView 这个控件去加载Url或富文本一类的内容了,今天还是关公门前耍大刀,班门弄斧的说一下其中 WebViewClient 的 shouldOverrideUrlLoading 方法。

已经了解掌握的咱就当复习一下,还不算知根知底的咱就接着看,放心,文章不长,很简短,几分钟的事情大笑

一. 什么时候调用:

    当新的 url 即将被加载的时候,也就是用户点击了 Webview 内容里面的一个超链接的时候会触发该方法的调用;

二. 为什么要实现:

    我们需要新的链接 url 就加载在当前 WebView 里面,或者我们需要自己的应用程序去处理响应该链接;

三. 怎么实现:

    1.仅需要实现在当前WebView加载该链接.

    webView.setWebViewClient(new WebViewClient());

    2.针对链接进行不同的处理.   

    webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if("www.baidu.com".equals(url)){
                    ......
                    return true;
                }else{
                    return false;
                }
            }
        });

咦,又有一个问题冒出来了,shouldOverrideUrlLoading 方法的返回值有什么用呢?别急,马上解说

/**
 * 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".
 *
 * @param view The WebView that is initiating the callback.
 * @param url The url to be loaded.
 * @return True if the host application wants to leave the current WebView
 *         and handle the url itself, otherwise return false.
 */
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    return false;
}

这是 Android 源码拷贝过来的 WebViewClient 的 shouldOverrideUrlLoading 的实现,其实到这里已经用不着我了,不过我非要反其道而行之,翻译一番。

大概意思就是:

    提供给当前应用一个机会去单独处理 WebView 即将加载的一个新链接。如果 WebViewClient 没有设置,也就是没有调用 WebView setWebViewClient 方法,那默认就会让用户去选择一个浏览器应用,比如系统浏览器去加载这个新的链接了。那如果 WebViewClient 是设置了的,返回 True 代表当前应用已经处理了这个新链接了,不需要你 WebView 再去加载这个链接了,当然了,返回 False 的话 WebView 就会横插一脚,去加载这个新的链接。

嗯,打完收工!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值