when I click on links in my app, they open in the same webview. I want them to open in an external browser.
I did this:
myWebView.setWebViewClient(new WebViewClient()
{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
returning false makes it load within the same webview, and returning "true" makes nothing happen when a link is clicked.
I looked at other questions but it seems that everyone else has the exact opposite problem. (they want links to load in their app)
what am I doing wrong?
In your WebViewClient
@Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url){
if (loadUrlExternally){
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
return true; //the webview will not load the URL
} else {
return false; //the webview will handle it
}
}
That way it opens a new browser window the same way any other app would.
Here's a more complete answer. Note: I'm calling from a fragment hence the getActivity() before startActivity()
@Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url)
{
//check if the url matched the url loaded via webview.loadUrl()
if (checkMatchedLoadedURL(url))
{
return false;
} else
{
getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
/**
* used to check if the loaded url matches the base url loaded by the fragment(mUrl)
* @param loadedUrl
* @return true if matches | false if doesn't or either url is null
*/
private boolean checkMatchedLoadedURL(String loadedUrl)
{
if (loadedUrl != null && mUrl != null)
{
// remove the tailing space if exisits
int length = loadedUrl.length();
--length;
char buff = loadedUrl.charAt(length);
if (buff == '/')
{
loadedUrl = loadedUrl.substring(0, length);
}
// load the url in browser if not the OTHER_APPS_URL
return mUrl.equalsIgnoreCase(loadedUrl);
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With