Android Webview触摸内容

Android Webview touch content

本文关键字:触摸 Webview Android      更新时间:2023-09-26

我想在字符串中获取我在webview中触摸到的标签的内容。

假设我有5个段落,并且我触摸其中一个,那么我想要字符串中该段落的内容。我怎样才能做到这一点?感谢

这很容易,但需要分部分完成,并且需要JavaScript。

1.-在您的网络视图中启用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检索到的String添加需要处理的任何内容。该类可以在创建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 中的所有调用