从 Android 上的 TextView 复制文本 [英] Copy text from TextView on Android
问题描述
我有一个 ListView
,其中每个项目都是一个 TextView
.
我想启用类似于 EditText
的长按行为,该行为显示默认上下文菜单,其中包含全选"、全部剪切"、全部复制"等项目.>
是否有一种简单的方法可以为 TextView
启用此功能?
我想我有一个解决方案.只需致电registerForContextMenu(yourTextView);
并且您的 TextView
将被注册以接收上下文菜单事件.
然后在您的 Activity
中覆盖 onCreateContextMenu
:
@Overridepublic void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {//用户长按你的TextViewmenu.add(0, v.getId(), 0, "你想在上下文菜单中显示的文本 - 我只使用复制");//将接收到的View转换为TextView,这样你就可以得到它的文本TextView yourTextView = (TextView) v;//将你的TextView的文本放在剪贴板中ClipboardManager 剪贴板 = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);clipboard.setText(yourTextView.getText());}
希望这可以帮助您和其他任何正在寻找从 TextView
I have a ListView
where each item is a TextView
.
I want to enable the long press behaviour similar to an EditText
that displays the default context menu with items like "Select all", "Cut all", "Copy all", etc.
Is there an easy way to enable this for a TextView
?
I think I have a solution.
Just call
registerForContextMenu(yourTextView);
and your TextView
will be registered for receiving context menu events.
Then override onCreateContextMenu
in your Activity
:
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
//user has long pressed your TextView
menu.add(0, v.getId(), 0, "text that you want to show in the context menu - I use simply Copy");
//cast the received View to TextView so that you can get its text
TextView yourTextView = (TextView) v;
//place your TextView's text in clipboard
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(yourTextView.getText());
}
Hope this helps you and anyone else looking for a way to copy text from a TextView
这篇关于从 Android 上的 TextView 复制文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!