Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebView - Intercept clicks

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.

<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?

like image 881
Ian Vink Avatar asked Jul 14 '10 20:07

Ian Vink


1 Answers

Then you have to set a WebViewClient to your WebView and override shouldOverrideUrlLoading and onLoadResource methods. Let me give you a simple example:

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         }     } } 
like image 191
Cristian Avatar answered Sep 19 '22 15:09

Cristian