2010-07-14 133 views
24

我已經使用WebView編寫了一個簡單的helloworld應用程序,該應用程序在我的資產文件夾的simple.html頁面上有一個鏈接到CNN。Android WebView - 攔截點擊

<a href="http://cnn.com">cnn.com</a> 

我怎樣才能捕捉到這個點擊我的活動,從航行停止的WebView,然後通知「http://CNN.com」被點擊的活動?

回答

65

然後,您必須將WebViewClient設置爲WebView並覆蓋shouldOverrideUrlLoadingonLoadResource方法。讓我舉個簡單的例子:

WebView yourWebView; // initialize it as always... 
// this is the funny part: 
yourWebView.setWebViewClient(yourWebClient); 

// somewhere on your code... 
WebViewClient yourWebClient = new WebViewClient(){ 
    // you tell the webclient you want to catch when a url is about to load 
    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, String url){ 
     return true; 
    } 
    // here you execute an action when the URL you want is about to load 
    @Override 
    public void onLoadResource(WebView view, String url){ 
     if(url.equals("http://cnn.com")){ 
      // do whatever you want 
     } 
    } 
} 
+0

對不起,我知道這是陳舊的,但它正是我正在尋找的除了....我的導航沒有完成。當用戶單擊WebView中的鏈接時,它會轉到shouldOverrideLoading並執行該操作,但不會完成導航。我希望它完成只是想嗅一下他們先選擇什麼。 – GPGVM 2012-05-04 18:01:52

+1

在這種情況下,你不應該在shouldOverrideUrlLoading – Cristian 2012-05-04 18:14:31

+1

中返回true,所以返回false,除非你真的想要中止。 – GPGVM 2012-05-04 18:17:22