0

I try to select text in webview, after I select text,I need to decide what to do next.not just copy the selected text.I have more choice for user to choose from.I mean, after user selected text in webview,could I prompt out a some button for further? I tried use emulateshiftheld to solve my problem.but google's docs said " This method is deprecated". also,I can't prompt out some choice button. you can clck the link to see what I mean. link: https://public.blu.livefilestore.com/y1pHhMR2iyIbQN7uJ2C-9CLLJBosWAZw2r4MvD0qyyTG-QWUM-06i6HFu4Fn4oaWnHMbDyTBOa-CPwN6PwoZNifSQ/select.jpg?download&psid=1

songtzu
  • 90
  • 2
  • 12
  • picture link https://public.blu.livefilestore.com/y1pHhMR2iyIbQN7uJ2C-9CLLJBosWAZw2r4MvD0qyyTG-QWUM-06i6HFu4Fn4oaWnHMbDyTBOa-CPwN6PwoZNifSQ/select.jpg?download&psid=1 – songtzu Jul 04 '12 at 04:51

2 Answers2

0

Pasting relevant code from WebView emulateShiftHeld() on Android Newer SDK's

/**
 * Select Text in the webview and automatically sends the selected text to the clipboard
 */
public void selectAndCopyText() {
    try {
     KeyEvent shiftPressEvent = new KeyEvent(0,0,KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_SHIFT_LEFT,0,0);
     shiftPressEvent.dispatch(mWebView);
    } catch (Exception e) {
        throw new AssertionError(e);
    }
} 
user1417430
  • 376
  • 2
  • 6
  • I wanna to let user have the chance to dicide what to do next. A.copy the selected text. B.share the selected text. so I need to override the callback of select text. – songtzu Jul 04 '12 at 05:43
0

The question is very old, but for other people here is a solution with javascript for API 19+. Just add this to your WebView:

public void getSelectedText(final SelectedTextInterface selectedTextInterface) {
    evaluateJavascript("(function(){return window.getSelection().toString()})()", new ValueCallback<String>() {
        @Override
        public void onReceiveValue(final String selectedText) {
            if (selectedText != null && !selectedText.equals("")) {
                //If you don't have a context, just call
                //selectedTextInterface.onTextSelected(selectedText);
                if (context instanceof Activity) {
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            selectedTextInterface.onTextSelected(selectedText);
                        }
                    });
                } else selectedTextInterface.onTextSelected(selectedText);
            }
        }
    });
}

public interface SelectedTextInterface {
    void onTextSelected(String selectedText);
}    

When you are done with selecting text, just call it with:

webView.getSelectedText(new YourWebView.SelectedTextInterface() {
    @Override
    public void onTextSelected(String selectedText) {
        //Your code here
    }
});    

I hope this may be useful for some people :-)

SaschaHa
  • 11
  • 2