127

现在我有一个加载 web 视图的应用程序,所有的点击都保留在应用程序中。我想做的是,当在应用程序中点击某个链接时,例如http://www.google.com,它会打开默认浏览器。如果有人有一些想法,请告诉我!

4

6 回答 6

211

我今天必须做同样的事情,我在 StackOverflow 上找到了一个非常有用的答案,我想在这里分享,以防其他人需要它。

来源(来自sven

webView.setWebViewClient(new WebViewClient(){
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
            view.getContext().startActivity(
                new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
});
于 2011-06-14T13:01:01.140 回答
39
WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl(https://whatoplay.com/);

您不必包含此代码。

// webview.setWebViewClient(new WebViewClient());

而是使用下面的代码。

webview.setWebViewClient(new WebViewClient()
{
  public boolean shouldOverrideUrlLoading(WebView view, String url)
  {
    String url2="https://whatoplay.com/";
     // all links  with in ur site will be open inside the webview 
     //links that start ur domain example(http://www.example.com/)
    if (url != null && url.startsWith(url2)){
      return false;
    } 
     // all links that points outside the site will be open in a normal android browser
    else
    {
      view.getContext().startActivity(
      new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
      return true;
    }
  }
});
于 2013-09-25T08:32:47.607 回答
14

您只需要添加以下行

yourWebViewName.setWebViewClient(new WebViewClient());

检查this以获取官方文档。

于 2015-03-09T00:18:34.160 回答
11

您可以为此使用 Intent:

Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("your Url"));
startActivity(browserIntent);
于 2010-11-20T04:42:22.803 回答
6

You can use an Intent for this:

Uri uriUrl = Uri.parse("http://www.google.com/"); 
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);  
startActivity(launchBrowser);  
于 2012-05-10T06:44:25.333 回答
2

由于这是有关 WebView 中外部重定向的首要问题之一,因此这里有一个 Kotlin 上的“现代”解决方案:

webView.webViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            val url = request?.url ?: return false
            //you can do checks here e.g. url.host equals to target one
            startActivity(Intent(Intent.ACTION_VIEW, url))
            return true
        }
    }
于 2021-02-18T08:23:16.230 回答