Android: Copy to clipboard selected text from a TextView

前端 未结 2 1250

Is there a possibility to copy to clipboard from a TextView UI component only the selected text?

I\'ve catched the long press event and I copied the full text to cli

2条回答
  •  悲&欢浪女
    2020-12-07 23:48

    you can do it this way:

    ClipboardManager myClipboard = myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    ClipData myClip;
    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();
    
    
    // copy to clipboard
    myClip = ClipData.newPlainText("text", text);
    myClipboard.setPrimaryClip(myClip);
    

    Replace EditText with TextView

提交回复
热议问题