Android WebView - 拦截点击次数

Ian*_*ink 26 android webview

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

<a href="http://cnn.com">cnn.com</a>
Run Code Online (Sandbox Code Playgroud)

如何捕获我的Activity上的单击,停止WebView导航,然后通知Activity 点击了" http://CNN.com "?

Cri*_*ian 71

然后你必须设置一个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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)