Android: Copy to clipboard selected text from a TextView

前端 未结 2 1252

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-08 00:10

    TextView tv;
    String stringYouExtracted = tv.getText().toString();
    int startIndex = tv.getSelectionStart();
    int endIndex = tv.getSelectionEnd();
    stringYouExtracted = stringYouExtracted.subString(startIndex, endIndex);
    ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    clipboard.setText(stringYouExtracted);
    

    EDIT (The previous is the full answer, but I ran into my answer by mistake so I would like to add):

    With Newer APIs, change the last two lines to :

    if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(stringYouExtracted);
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", stringYouExtracted);
                clipboard.setPrimaryClip(clip);
    }
    

    "Copied Text" is a title for your COPY entity in newer APIS

提交回复
热议问题