如何在默认浏览器和WebView Android中的所有内部链接中打开外部URL? [英] How to open external URL in default browser and all internal links in WebView Android?

查看:518
本文介绍了如何在默认浏览器和WebView Android中的所有内部链接中打开外部URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面中使用WebView,并在WebView中使用本地文件assets进行显示,但在外部主网站(非本地)的HTML主页中,我想在用户的默认浏览器中仅打开该链接设备

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

这是我在'onCreate'方法中的代码

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");

当我运行该应用程序时,内部链接可以正常工作,但是外部链接"www.apple.com"在网络视图中可以访问

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

我搜索了相同的问题并找到了此解决方案,但外部链接仍在WebView中打开

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);

和班级

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;
        }
    }
}

推荐答案

更改

  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;
  }

 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;

注意:将mContext替换为您的活动上下文.

Note : replace mContext with your activity context.

这篇关于如何在默认浏览器和WebView Android中的所有内部链接中打开外部URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆