It is time for another WebView example. This time on how you can intercept any attempts at loading a web page and redirect the user to a different URL instead.
This can be achieved simply by registering a WebViewClient which overrides the shouldOverrideUrlLoading() method in which you tell the WebView to load a different URL from the one the user had requested.
The example below loads lexandera.com first, but when the user clicks any link on the page, he is redirected to yahoo.com:
WebView browser = (WebView)findViewById(R.id.browser);
browser.setWebViewClient(new WebViewClient() {
/* On Android 1.1 shouldOverrideUrlLoading() will be called every time the user clicks a link,
* but on Android 1.5 it will be called for every page load, even if it was caused by calling loadUrl()! */
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
/* intercept all page load attempts and load yahoo.com instead */
String myAlternativeURL = "http://yahoo.com";
if (!url.equals(myAlternativeURL)) {
view.loadUrl(myAlternativeURL);
return true;
}
return false;
}
});
browser.loadUrl("http://lexandera.com/");
Please note that calling loadUrl() does not trigger the shouldOverrideUrlLoading() method, which means that we do not need to worry about endless recursion when calling loadUrl() from within shouldOverrideUrlLoading()!
UPDATE: The above statement is no longer true for Android 1.5! Calling loadUrl() will now also trigger the shouldOverrideUrlLoading() method! This means that you need to make sure that you are not creating an infinite loop when calling loadUrl() from shouldOverrideUrlLoading()!
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=ed91eca5-2c5e-4b86-8b88-8af5a1b703f7)
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=bb22593d-ec9d-4064-9842-2bcb7fae4d4f)
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=62e34ae6-3382-45cb-b4f5-f08a367c4a80)
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=b89819f7-2769-4fb9-91f8-ab40a0b3e67b)
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=75a6582e-c459-4c4e-848b-e48a050ab4c9)