Skip to content Skip to sidebar Skip to footer

Android - Highlight A Word/phrase In A Webview

I want to select Text from Webview And Then Highlight only selected apparition of that word. someone has an idea? with javascript does not work because getSelection function return

Solution 1:

As far as I can understand, you can't select text on an Android touch device like you can on a desktop browser (with your mouse).

It seems like the way text is selected on android device only can be copied into the Clipboard or used by the native "Share" app.

Selecting the text => copy it into Clipboard => use the ClipboardManager to fetch it back.

I might is not as simple and smooth as you was hoping for, but maybe it will work out for you :)

Once you have the value of the selected text, your can always pass it to a javascript function that search/replace for it in your html and highlights it, by adding/padding some html to it.

Link to ClipboardManager. http://developer.android.com/reference/android/text/ClipboardManager.html

Here's a demo of fetching selected text with your mouse on a regular desktop browser:

http://bit.ly/AwggX9

Try running the same with your Android device. The text selection doesn't work the same way. I guess its the Share/Clipboard manager that handles the selection, and not the browser itself.

Good luck, hope you find a solution that works, and will be happy to hear about it.

Solution 2:

Have you looked into:

mainpage.showFindDialog("Alice", true);

where mainpage is the WebView...

This will popup above the webview a bar where the text is entered - and then highlight the first occurrence of the text. There are arrows to jump to the next, etc...

Unless you mean you wish to highlight certain words - and have them stay that way - then you need to inject some javascript to do a highlighting function.

Solution 3:

The following code will copy your text to clipboard then from clipboard fetch the text and search it..

privatevoidemulateShiftHeld(WebView view)
 {
     try
     {
         KeyEventshiftPressEvent=newKeyEvent(0, 0, KeyEvent.ACTION_DOWN,
                                                 KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
         shiftPressEvent.dispatch(view);

     }
     catch (Exception e)
     {
         Log.e("dd", "Exception in emulateShiftHeld()", e);
     }
 }

The following code will highlight you the text you have selected...

ClipboardManager ClipMan = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipMan.setText(ClipMan.getText().toString());
wb.findAll(ClipMan.getText().toString());
try
{
    Method m = WebView.class.getMethod("setFindIsUp", Boolean.TYPE);
    m.invoke(wb, true);
}
catch (Throwable ignored){}

Post a Comment for "Android - Highlight A Word/phrase In A Webview"