2012-08-22 55 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 –