Highlight the selected text in webview. [Android]

妖精的绣舞 提交于 2021-02-08 08:33:28

问题


I have certain text in the web view. I can select those text . I want to highlight those text but I have no idea how to do it. Anyone having any idea about it, please help! Thanx!


回答1:


you need to run java script

 public static String Highlightscript = " <script language=\"javascript\">" +

    "function highlightSelection(){" +
    "var userSelection = window.getSelection();" + 
    "for(var i = 0; i < userSelection.rangeCount; i++)"
    + "  highlightRange(userSelection.getRangeAt(i));" +
     "}" +
    "function highlightRange(range){"+
    "span = document.createElement(\"span\");"+
    "span.appendChild(range.extractContents());"+
    "span.setAttribute(\"style\",\"display:block;background:#ffc570;\");"+
    "range.insertNode(span);}"+
    "</script> ";

and

  webView.loadUrl("javascript:highlightSelection()");

make sure you enabled javascript

WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);



回答2:


In Android 4.1(jellybean), WebView.findAll() is deprecated, we should use WebView.findAllAsync instead.

reference

Wish this help:)



来源:https://stackoverflow.com/questions/45993571/highlight-the-selected-text-in-webview-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!