2012-05-09 60 views
0

如何獲取用戶在webview中點擊的鏈接?示例:如果用戶點擊PDF,我的webview會將用戶帶到列出信息和PDF的網站。我想要獲取用戶點擊的PDF文件的鏈接並將其放入Google的在線查看器。我有的代碼不起作用,因爲它不攔截點擊鏈接。有任何想法嗎?Android - 在webview中獲取鏈接用戶點擊

以下是我有:

webview.setWebViewClient(new WebViewClient() { 
     public boolean shouldOverrideUrlLoading(WebView view, String url) { 
      // do your handling codes here, which url is the requested url 
      // probably you need to open that url rather than redirect: 
      if (url.startsWith("tel:")) { 
       startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url))); 
      } else if (url.startsWith("mailto:")) { 
       url = url.replaceFirst("mailto:", ""); 
       url = url.trim(); 
       Intent i = new Intent(Intent.ACTION_SEND); 
       i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, 
         new String[] { url }); 
       startActivity(i); 

      } else if (url.startsWith("geo:")) { 
       try { 
       } catch (Exception e) { 
        System.out.println(e); 
       } 

      } else if (url.endsWith("pdf")) { 
       try{ 
        String pdf = (url); 
        webview.loadUrl("http://docs.google.com/viewer?url=" + pdf); 
        } 
        catch (ActivityNotFoundException e) 
        { 
        Toast.makeText(atcFaa.this, "No PDF Viewer Installed", Toast.LENGTH_LONG).show(); 
        } 

      } 

      else { 
       view.loadUrl(url); 
      } 
      return true; 
      // then it is not handled by default action 
     } 
    }); 
webview.loadUrl("http://www.somewebsite.com/publications/"); 
} 

回答

4

我想你想覆蓋的方法是WebViewClient.shouldInterceptRequest(WebView view, String url)

public WebResourceResponse shouldInterceptRequest (WebView view, String url) 
  • 通知資源請求的主機應用程序,並允許 應用返回數據。如果返回值爲空,則WebView將繼續像平常一樣繼續加載資源。否則,將使用 返回響應和數據。注意:此方法由 網絡線程調用,因此客戶端在訪問 私有數據時應該謹慎行事。參數

看到webview shouldinterceptrequest example

+0

我看到最小的SDK版本是11,因爲在這個例子說。我正在爲版本10構建(對於仍然在2.3.3薑餅上的人)。我唯一的選擇是升級到下一個版本,11? – user1363871

相關問題