0

我尝试在 webview 中选择文本,选择文本后,我需要决定下一步要做什么。不仅仅是复制选定的文本。我有更多的选择供用户选择。我的意思是,在用户在 webview 中选择文本后,可以我提示了一些按钮以获取更多信息?我尝试使用 emulateshiftheld 来解决我的问题。但谷歌的文档说“这种方法已被弃用”。另外,我无法提示某些选择按钮。你可以点击链接看看我的意思。链接:https ://public.blu.livefilestore.com/y1pHhMR2iyIbQN7uJ2C-9CLLJBosWAZw2r4MvD0qyyTG-QWUM-06i6HFu4Fn4oaWnHMbDyTBOa-CPwN6PwoZNifSQ/select.jpg?download&psid=1

4

2 回答 2

0

在 Android 较新的 SDK 上粘贴来自 WebView emulateShiftHeld() 的相关代码

/**
 * 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);
    }
} 
于 2012-07-04T05:32:51.407 回答
0

这个问题很老了,但对于其他人来说,这里是 API 19+ 的 javascript 解决方案。只需将其添加到您的 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);
}    

完成选择文本后,只需使用以下命令调用它:

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

我希望这可能对某些人有用:-)

于 2017-01-06T10:27:35.237 回答