Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
911 views
in Technique[技术] by (71.8m points)

android - How to get the selected text of webview in ActionMode override

I am adding some custom menu items in the Contextual Action Menu. I need to give a web search feature with the words selected in the WebView.

I override the ActionMode using this code.

@Override
    public void onActionModeStarted(ActionMode mode) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            if (mActionMode == null) {
                mActionMode = mode;
            Menu menu = mode.getMenu();

            mode.getMenuInflater().inflate(R.menu.menu_search, menu);
        }
    }
    super.onActionModeStarted(mode);
}


public void onContextualMenuItemClicked(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_search:
            //HERE I WANT TO GET THE TEXT: HOW CAN I?
            break;
    }

    if (mActionMode != null) {
        mActionMode.finish();
    }
}

I want to search my site using the word selected by the user in the webview, but I couln't get the way to get the selected text. How could i get that, any one please help.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The only way to get text selection from a WebView is based on javascript. This is not specific to the action mode, this is how WebView text selection is supposed to be retrieved according to WebView developers' point of view. They deliberately decided to not provide an API to access text selection from Java.

The solution comprise 2 approaches.

With Android API >= 19 you can use evaluateJavascript:

webview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
    @Override
    public void onReceiveValue(String value)
    {
        Log.v(TAG, "SELECTION:" + value);
    }
});

On older builds your only resort is a custom javascript interface with a single method accepting String, which you should call via webview.loadUrl passing the same thing:

webview.loadUrl("javascript:js.callback(window.getSelection().toString())");

where js is the attached javascript interface:

webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new WebAppInterface(), "js");

and

public class WebAppInterface
{
    @JavascriptInterface
    public void callback(String value)
    {
        Log.v(TAG, "SELECTION:" + value);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...