Codementor Events

How to select + copy text from Android TextView?

Published Mar 13, 2017
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.

Like registerForContextMenu(yourtextview)

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:

device-2013-04-17-161218.png

device-2013-04-17-161237.png

Discover and read more posts from Hardik Joshi
get started
post commentsBe the first to share your opinion
Show more replies