How to get the selected text in android webview

2019-01-20 04:28发布

问题:

I need to get the selected text from webview and have to highlight the text permanently. I tried as selecting the text and while i am attempting to get the text using clipboard it showing me null pointer exception at "clipboard.getText()". I have tried code as

ClipboardManager mClipboard =
        (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

 KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
                                                    KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
shiftPressEvent.dispatch(webview);
 if(mClipboard!=null)
     {
       String text = mClipboard.getText().toString();
       Toast.makeText(this, "select_text_now     "+text, Toast.LENGTH_LONG).show();
     }

I need to get the selected text for highlight futher..please help me..

回答1:

I have filed an Android bug for this: Issue 24842: WebView should make getSelection public. If you look at the ticket, you'll see some various workarounds.

Note that the code you posted is roughly similar to emulateShiftHeld which is deprecated in 4.0, which is probably why it is working in 2.2 and not in 4.0.