How to select + copy text from Android TextView?
Select + copy text in a TextView?
Generally, we can copy / paste the value from EditText
by long click. It is an in-build functionality for Android. Now, let's say you have the same requirement in TextView
. You would have to use registerForContextMenu
.
registerForContextMenu(yourtextview)
Like Your TextView
will be registered for receiving context menu events.
You would have to override the onCreateContextMenu()
method. Here's the entire code:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtcopytext = (TextView) findViewById(R.id.txtcopytext);
registerForContextMenu(txtcopytext);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// user has long pressed your TextView
menu.add(0, v.getId(), 0,
"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());
}
Here are some example screenshots: