安卓:复制到从一个TextView剪贴板选定文本剪贴板、文本、TextView

2023-09-12 08:43:53 作者:任凭寂寞沸腾

有没有复制从一个TextView UI组件到剪贴板可能只有选定的文本?

我擦肩而过,长preSS事件,我复制全文到剪贴板,但现在我要指定的开始和选择结束从一个TextView复制。

感谢你。

解决方案

  TextView的电视;
字符串stringYouExtracted = tv.getText()的toString。
INT的startIndex = tv.getSelectionStart();
INT endIndex的= tv.getSelectionEnd();
stringYouExtracted = stringYouExtracted.subString(在startIndex,endIndex的);
ClipboardManager剪贴板=(ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(stringYouExtracted);
 

剪贴板增强工具下载 CopyQ中文最新版下载5.0.0

修改(将previous是完整的答案,但我遇到了错误我的答案,所以我想补充)的

使用较新的API,最后两行更改为:

 如果(android.os.Build.VERSION.SDK_INT< android.os.Build.VERSION_ codeS.HONEYCOMB){
    android.text.ClipboardManager剪贴板=(android.text.ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setText(stringYouExtracted);
} 其他 {
    android.content.ClipboardManager剪贴板=(android.content.ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
    android.content.ClipData夹= android.content.ClipData.newPlainText(复制的文本,stringYouExtracted);
            clipboard.setPrimaryClip(夹);
}
 

复制的文本是您COPY的实体在新API的标题

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 clipboard, but now I want to specify the start and the end of the selection to be copied from a TextView.

Thank you.

解决方案

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