How to open external URL in default browser and all internal links in WebView Android?

ぃ、小莉子 提交于 2019-12-06 15:33:00

问题


I am using WebView in my page and using local file assets to displaying in WebView but in main HTML page external website (not local) and I want to open just that link in default Browser on the users device

This is my code in 'onCreate' method

WebView v;

v=(WebView) rootView.findViewById(R.id.webView1);
v.getSettings().setJavaScriptEnabled(true);
WebViewClient vc= new WebViewClient();
v.setWebViewClient(vc);
v.loadUrl("file:///android_asset/home.html");

When I run the application the internal link is working good but the external link "www.apple.com" en in the web view

I searched the same question and found this solution but still external link opens in WebView

WebView webView = (WebView) rootView.findViewById(R.id.webView1);
webView.setWebViewClient(new MyWebViewClient());
String url = "file:///android_asset/home.html";
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);

and class

class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(url.contains("http")){ // Could be cleverer and use a regex
            return super.shouldOverrideUrlLoading(view, url); // Leave webview and use browser
        } else {
            view.loadUrl(url); // Stay within this webview and load url
            return true;
        }
    }
}

回答1:


Change

  if (url.contains("http")) { // Could be cleverer and use a regex
    return super.shouldOverrideUrlLoading(view, url); // Leave webview and use browser
  } else {
    view.loadUrl(url); // Stay within this webview and load url
    return true;
  }

to

 if (url.contains("http")) { // Could be cleverer and use a regex
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    mContext.startActivity(intent);
    return true;
 }
 return false;

Note : replace mContext with your activity context.



来源:https://stackoverflow.com/questions/30933556/how-to-open-external-url-in-default-browser-and-all-internal-links-in-webview-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!