2

许多 Android 开发人员实现了自己的 webview。尽管在 stackoverflow 上讨论了很多与此主题相关的问题,但这可能是造成这种不明确的原因。

要在您的 WebView 中打开链接,android 开发人员需要定义自己的 webview。

开发者网站之一是否有错误?API级别之间有区别吗?shouldOverrideUrlLoading 最干净和最好的用法是什么?

答案将帮助我们的团队和许多其他使用 android webviews 的开发人员。谢谢。

4

3 回答 3

3

In case you decide to implement WebViewClient:

webView.setWebViewClient(new WebViewClient()
{
  @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url)
  {
    // My own condition to decide if I should skip URL loading
    boolean avoidURLLoading = ...

    if (avoidURLLoading)
    {
      // Ask the WebView to avoid loading the URL,
      // I want to manage this case on my own.
      return true;
    }
    else
    {
      // Let the WebView load the URL 
      return false;
    }
  };
});

If you don't implement WebViewClient, every time you'll ask the WebView to load an URL with the loadUrl method, it will ask the Activity Manager to find a proper app to load the URL (typically a web browser installed in the device).

The default implementation of shouldOverrideUrlLoading in WebViewClient is

public boolean shouldOverrideUrlLoading(WebView view, String url)
{
  return false;
}

So if you just write something like this

webView.setWebViewClient(new WebViewClient());

the URL will load inside your own WebView and not in an external web browser.

You'll typically return true in shouldOverrideUrlLoading when you want to modify the URL and then load the new one with another loadUrl call or when you just want to avoid loading the URL and handle the request in a different way.

The behavior in your example

public boolean shouldOverrideUrlLoading(WebView view, String url)
{
  view.loadUrl(url);
  return true;
}

is equivalent to

public boolean shouldOverrideUrlLoading(WebView view, String url)
{
  return false;
}

because you're telling the WebView to avoid handling the URL loading (return true), but you're also making another request with view.loadUrl(url) so in fact you end up loading the URL.

于 2012-06-03T00:04:27.647 回答
0

为了在当前 WebView(不是浏览器)中打开链接,您应该像这样返回 false:

mWebView.setWebViewClient(new WebViewClient(){
        public boolean shouldOverrideUrlLoading(WebView view, String url){

            return false;  

        }
    });
于 2012-06-02T20:56:37.577 回答
0

只要你实现 setWebViewClient(..) 我的答案和 axample 做同样的事情。另一方面,如果您不实现它,浏览器将启动 instaed。

于 2012-06-02T21:45:35.977 回答