6

The browser does this by calling public void emulateShiftHeld() method on the WebView which is hidden in the SDK.
Any other options?

yanchenko
  • 56,576
  • 33
  • 147
  • 165

2 Answers2

8

From the class that extends WebView:

public void selectAndCopyText() {
    try {
        Method m = WebView.class.getMethod("emulateShiftHeld", null);
        m.invoke(this, null);
    } catch (Exception e) {
        e.printStackTrace();
        // fallback
        KeyEvent shiftPressEvent = new KeyEvent(0,0,
             KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_SHIFT_LEFT,0,0);
        shiftPressEvent.dispatch(this);
    }
}

And then you have to use ClipboardManager to watch for new text.

Works on Android 1.5 - 2.3. emulateShiftHeld() made public since 2.2.

yanchenko
  • 56,576
  • 33
  • 147
  • 165
  • As long as the user "cooperates" by **manually** selecting the text. See http://stackoverflow.com/questions/5250290/why-doesnt-this-motionevent-simulation-work – Regex Rookie Mar 09 '11 at 20:32
  • Under Anroid 4.0.3 m.invoke(webView, null) cause native crash 09-21 23:20:49.151: A/libc(4103): Fatal signal 11 (SIGSEGV) at 0x00000014 (code=1) – Mike Keskinov Sep 21 '12 at 15:34
  • Sorry I don't get this.. I've added selectAndCopyText() in my class that extends WebView, but where do I call this function to allow text in WebView to be selectable? – Bruce Nov 24 '13 at 03:40
3

This chunk of code does the exact same thing as emulateshiftheld(). It allows the user to select text. Then automatically copies it to the clipboard.

        KeyEvent shiftPressEvent = new KeyEvent(0,0,
                 KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_SHIFT_LEFT,0,0);
            shiftPressEvent.dispatch(portal);
user481022
  • 41
  • 3