有没有办法在全球范围内识别用户文本选择事件?

时间:2015-04-14 07:22:19

标签: android android-service clipboard

当用户在任何应用程序上选择一个单词(点击以突出显示)时,有没有办法从我的Android应用程序中识别该事件。目前我正在使用剪贴板监听器来识别用户何时将某些内容复制到剪贴板。但我想在用户复制之前识别这个词(当时用户选择这个词)

仅供参考:我正在使用以下方法访问剪贴板更改服务

private void performClipboardCheck() {
    ClipboardManager cb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    if (cb.hasPrimaryClip()) {
        ClipData cd = cb.getPrimaryClip();
        if (cd.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){
            System.out.println("Copy performed");
            if(cb.getText().toString().contains(" ")){
                //do something
            }else{
                //do something else 
            }


        } 
    }} 

1 个答案:

答案 0 :(得分:0)

您可以通过这种方式获取所选文本格式编辑文本:

EditText editText = (EditText) findViewById(R.id.editText3);
                int min = 0;
                int max = editText.getText().length();
                if (editText.isFocused()) {
                    final int selStart = editText.getSelectionStart();
                    final int selEnd = editText.getSelectionEnd();
                    min = Math.max(0, Math.min(selStart, selEnd));
                    max = Math.max(0, Math.max(selStart, selEnd));
                }
                // here is your selected text
                final CharSequence selectedText = editText.getText().subSequence(min, max);
                String text = selectedText.toString();

然后为了将文本复制到剪贴板,

myClip = ClipData.newPlainText("text", text );
        myClipboard.setPrimaryClip(myClip);

如果要从editText替换所选文本,

                int min2 = 0;
                int max2 = editText.getText().length();
                if (editText.isFocused()) {
                    final int selStart = editText.getSelectionStart();
                    final int selEnd = editText.getSelectionEnd();
                    min2 = Math.max(0, Math.min(selStart, selEnd));
                    max2 = Math.max(0, Math.max(selStart, selEnd));
                }
                ClipData abc = myClipboard.getPrimaryClip();
                ClipData.Item item11 = abc.getItemAt(0);
                String text1 = item11.getText().toString();
                editText.getText()
                        .replace(min2, max2, text1, 0, text1.length());