Android: Programatically trigger text selection mode in a WebView on Jelly Bean
Asked Answered
I

1

6

I need to programatically trigger text selection mode in a WebView, but the code I have used does not work on Jelly Bean?

I have been using the following code but it no longer works on Android 4.1 (Jelly Bean) because WebView.selectText, emulateShiftHeld, and the key dispatch are no longer supported on Jelly Bean.

Following code that works on all versions up to ICS is based on: How to enable the default highlight menus in android webview?

public void selectAndCopyText() {
    try {
        // ICS
            WebView.class.getMethod("selectText").invoke(this);
        } catch (Exception e1) {
        try {
            Method m = WebView.class.getMethod("emulateShiftHeld", (Class[])null);
            m.invoke(this, (Object[])null);
        } catch (Exception e2) {
            // fallback
            KeyEvent shiftPressEvent = new KeyEvent(0,0,
                     KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_SHIFT_LEFT,0,0);
            shiftPressEvent.dispatch(this);
        }
    }
}

How do I implement similar functionality that works on Jelly Bean?

Inglis answered 9/8, 2012 at 10:54 Comment(2)
Hey @Martin, have you finally solved this??Specify
Hi davids, I have listed a potential solution in teh comments here: #7581631Inglis
I
2

I have listed a potential solution in the comments here: How to enable the default highlight menus in android webview?

Here is the content of the potential solution: After analyzing android.webkit.WebViewClassic I have had some success with the following:

KeyEvent enterEvent = new KeyEvent(0,0,KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_ENTER,0,0);
enterEvent.dispatch(this); 

I thought more might be required as I needed to scroll down the WebView a little before the above worked when using an emulator, but after testing on a real JellyBean device the above seems to work fine.

Inglis answered 21/9, 2012 at 19:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.