Question

It's known to be difficult to get selected text in a WebView because WebView text selection is actually handled by a private class, WebTextView.

However, with the recently released Android 4.0 Design guidelines, there seems to be a glimmer of hope of achieving this through contextual action bars (CABs). It says:

Use CABs whenever you allow the user to select data via long press. You can control the action content of a CAB in order to insert the actions you would like the user to be able to perform.

Am I misinterpreting this? Is there a way to retrieve selected text from a WebView via a CAB?

After a long click and text selection mode begins, I can currently detect when the ActionMode starts and modify the original copy/paste Menu; however, I can't quite figure out how to actually retrieve the selected text.

Was it helpful?

Solution

You can't do that yet with the current API.

I filed a feature request for this - Issue 24841: WebView should allow applications to supply a custom Contextual Action Bar http://code.google.com/p/android/issues/detail?id=24841

Basically, WebView in 4.0 has hardcoded its own Contextual Action Bar (CAB). That CAB has a reference back to the WebView and with that reference, it can get the selected text. I'm not sure how you were able to detect the ActionMode starting and modify the menu, but if you were able to do all of that, then you are stuck because getSelection() is package-private currently. I filed that as a separate issue and linked it to the previous issue above.

OTHER TIPS

You can use javascript to get the selected text: window.getSelection(), and use WebView's addJavascriptInterface function to return the result.

thanks for your information, I have solved a hard issue.. I just want to add some function into the actionmode. The following is my code, May be helpful to others.

@Override
public ActionMode onWindowStartingActionMode(Callback callback) {
    // TODO Auto-generated method stub
    ActionMode mode = super.onWindowStartingActionMode(callback);
    mode.getMenuInflater().inflate(R.menu.actions, mode.getMenu());
    mode.getMenu().findItem(R.id.action_add).setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            // TODO Auto-generated method stub
            Log.i("", "onMenuItemClick add ");
            return false;
        }
    });
    return mode;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top