Android:从 TextView 复制到剪贴板选定的文本 [英] Android: Copy to clipboard selected text from a TextView

查看:18
本文介绍了Android:从 TextView 复制到剪贴板选定的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能仅将所选文本从 TextView UI 组件复制到剪贴板?

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

我已经捕捉到长按事件并将全文复制到剪贴板,但现在我想指定要从 TextView 复制的选择的开始和结束.

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.

谢谢.

推荐答案

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);

<小时>

编辑(上一个是完整的答案,但我误会了我的答案,所以我想补充一下):

对于较新的 API,将最后两行更改为:

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" 是新 APIS 中 COPY 实体的标题

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

这篇关于Android:从 TextView 复制到剪贴板选定的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆