2012-08-22 53 views
1

我想要在webview中以字符串的形式獲取該標記的內容。Android Webview觸摸內容

假設我有5個段落,我碰到一個然後我想要在字符串中的段落的內容。 我該如何做到這一點? 謝謝

回答

0

好吧,這很容易,但你需要做的部分,你需要JavaScript。

1.-在您的webview中啓用JavaScript。

web.getSettings().setJavaScriptEnabled(true); //"web" is the object of type WebView 

2.-在WebView和Html之間創建一個JavaScript接口。

public class JavaScriptInterface { 

    private Handler myHandler = new Handler(); 

    public void getParagraph(final String paragraph){ 
     myHandler.post(new Runnable() { 
      @Override 
      public void run() { 
       //Do something with the String 
      } 
     }); 
    } 
} 

注:方法運行裏面,你會添加任何你需要從HTML中檢索到的字符串處理。如果您要從其他活動使用相同的行爲,則可以在創建WebView的類中創建此類,也可以將其作爲單獨的類創建。

3.-將接口發送到WebView。

web.addJavascriptInterface(new JavaScriptInterface(), "android"); 
/* In this case "android" is the name that you will use from the Html to call 
your methods if is not too clear yet, please keep reading */ 

4.-您需要將onClick事件處理程序添加到您的每個P標籤。

<p onclick="android.getParagraph(this.innerText);">Text inside the paragraph</p> 
/*android was the name we set for the interface in step 3, getParagraph is the name 
of the method created on step2,"this.innerText" retrieves the text inside the paragraph*/ 

注:所有你對我的例子中看到的名稱可以改變,但是如果你改變Java類的名字記得更改HTML所有呼叫

+0

我看過的文檔。但是我只使用過一次這種方法,而且它稍微有些不同,我想也許額外的類型是'UNKNOWN_TYPE'時可能包含段落字符串。但沒有時間來測試這個理論,所以我想我會與OP分享它,以防它可以幫助他們。任何這看起來像一個很好的解決方案感謝分享。 – FoamyGuy

+0

您的歡迎[@FoamyGuy](http://stackoverflow.com/users/507810/foamyguy),我知道你做了好事情:D –