Reputation: 2461
I am having a webview, the webview might contain a webpage with two different types of links. What I want is that, if the user clicks on a link which contains http://webpagename.com
it should open the link in the phone's browser. If the user clicks on the second type of link, which does not have http://
he should be redirected to a new activity. Right now what is happening is that, the links with http://
are opening up both in webviews and browsers. But, the links not having http://
is showing Web Page not available.
The code to handle onclick link in webview:
// to know which link is clicked
holder.webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
holder.webView.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
if (url != null && url.startsWith("http://")) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return null;
}
else {
Log.e("URL: ", url);
System.out.println(url.replace(url.substring(0,url.lastIndexOf("/")+1), ""));
return null;
}
}
/**
* Return WebResourceResponse with CSS markup from a String.
*/
});
return super.shouldOverrideUrlLoading(view, url);
}
});
What should I do to make sure the http://
links always opens in the browser and the other links open an activity but nothing opens in the webview?
Upvotes: 1
Views: 831
Reputation: 39191
From the docs for WebViewClient
, the shouldOverrideUrlLoading()
method:
Returns
True if the host application wants to leave the current WebView and handle the url itself, otherwise return false.
Since you're handling the WebView's content and the redirects to Activities, this method should explicitly return true
, rather than the super
method's return value.
From your description and code, it doesn't appear that you need to override the shouldInterceptRequest()
method.
holder.webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (url != null && url.startsWith("http://"))
{
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
else
{
Log.e("URL: ", url);
System.out.println(url.replace(url.substring(0, url.lastIndexOf("/") + 1), ""));
// Start your app's Activity here
}
return true;
}
});
Upvotes: 1