How to enable the default highlight menus in android webview?
Asked Answered
D

3

21

How to enable the default text highlights menu like: Copy/Paste/Search/Share in android webview ?

enter image description here

Denten answered 28/9, 2011 at 9:33 Comment(0)
A
4

Working on Android 1.5 - 2.3 you can use emulateShiftHeld() made public since 2.2 but now is deprecated. this method put your WebView into text selection mode.

https://developer.android.com/reference/android/webkit/WebView.html#emulateShiftHeld%28%29

Unfortunately there's no copy/paste/search/share function integrated in Android, since Android 2.0 the text selection can be driven by touch but other than that, there's no other thing you can do.

Androsphinx answered 24/11, 2011 at 16:29 Comment(2)
Any javascript related stuff you can suggest to do this?Bumble
@Drax The question was mis-tagged. WebView is a Java class, and Java != JavaScript (and there is no "javascript"). However, you could try to emulate this in a document displayed by a WebView with DOM scripting using touch events.Sensuality
P
2

I found a workaround for this Check out method selectText() on WebView (it's not in API, but can be invoked using reflection)

here is my full method source code:

 public void startTextSelection() {
        try {
            WebView.class.getMethod("selectText").invoke(this);
        } catch (Exception e) {
            try {
                WebView.class.getMethod("emulateShiftHeld").invoke(this);
            } catch (Exception e1) {
                KeyEvent shiftPressEvent = new KeyEvent(0, 0,
                        KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
                shiftPressEvent.dispatch(this);
                Toast.makeText(getContext(), R.string.select_text, Toast.LENGTH_LONG).show();
            }
        }
    }

Works on ICS too.

Precautionary answered 19/6, 2012 at 8:0 Comment(5)
I used the above code but unfortunately selectText has been completely removed from Android 4.1 (Jellybean) so this will no longer work. Any suggestions for 4.1?Wistrup
@Wistrup well i will have to look into the source code of 4.1 will get back to you as soon as i find the solution :)Precautionary
After analyzing android.webkit.WebViewClassic I have had some success with:Wistrup
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); but more may be required as I need to scroll down the WebView a little before the above works.Wistrup
@Wistrup i think there will be some method which does this i haven't got time to look into source code but i will look into it as soon as possible ;)Precautionary
S
-1

Try this:

 mWebView.setHapticFeedbackEnabled(true);
 mWebView.setLongClickable(true);
Slosh answered 24/11, 2011 at 15:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.