Android WebView - 拦截点击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3250034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:18:23  来源:igfitidea点击:

Android WebView - Intercept clicks

androidwebview

提问by Ian Vink

I have written a simple helloworld app with a WebView which has a link to CNN on a simple.html page in my asset folder.

我编写了一个带有 WebView 的简单 helloworld 应用程序,该应用程序在我的资产文件夹中的 simple.html 页面上有一个指向 CNN 的链接。

<a href="http://cnn.com">cnn.com</a>

How can I capture the click on this on my Activity, stop the WebView from navigating, and then inform the Activity that "http://CNN.com" was clicked?

如何在我的 Activity 上捕获对此的点击,停止 WebView 导航,然后通知 Activity已单击“ http://CNN.com”?

回答by Cristian

Then you have to set a WebViewClientto your WebViewand override shouldOverrideUrlLoadingand onLoadResourcemethods. Let me give you a simple example:

然后你必须为WebViewClient你的WebView和覆盖shouldOverrideUrlLoadingonLoadResource方法设置一个。我给你举个简单的例子:

WebView yourWebView; // initialize it as always...
// this is the funny part:
yourWebView.setWebViewClient(yourWebClient);

// somewhere on your code...
WebViewClient yourWebClient = new WebViewClient(){
    // you tell the webclient you want to catch when a url is about to load
    @Override
    public boolean shouldOverrideUrlLoading(WebView  view, String  url){
        return true;
    }
    // here you execute an action when the URL you want is about to load
    @Override
    public void onLoadResource(WebView  view, String  url){
        if( url.equals("http://cnn.com") ){
            // do whatever you want
        }
    }
}