2011-12-15 101 views
7

當我點擊我應用中的鏈接時,它們在同一個webview中打開。我希望他們在外部瀏覽器中打開。Android Webview,使網址在不同的瀏覽器中打開

我這樣做:

myWebView.setWebViewClient(new WebViewClient() 
{ 
       @Override 
       public boolean shouldOverrideUrlLoading(WebView view, String url) { 
        return false; 
       } 

}); 

返回false使得它在同一網頁視圖內加載,並返回「真」,使點擊一個鏈接時沒有發生。

我看了其他問題,但似乎每個人都有完全相反的問題。 (他們想要鏈接加載到他們的應用程序)

我做錯了什麼?

+0

鏈接是真正的鏈接(url)還是JavaScript片段? – 2011-12-15 18:22:05

+0

真正的html鏈接。 – CQM 2011-12-15 19:03:16

回答

12

在你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 
    } 
} 

這樣,它會打開一個新的瀏覽器窗口,以同樣的方式任何其他應用程序將。

1

下面是一個更完整的答案。注意:我是從片段調用的,因此在startActivity()之前調用getActivity()

@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; 
    } 
相關問題