How to Copy Text to Clip Board in Android?

Darshan Gowda picture Darshan Gowda · Oct 8, 2013 · Viewed 189k times · Source

Can anybody please tell me how to copy the text present in a particular textview to clipboard when a button is pressed?

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainpage);
        textView = (TextView) findViewById(R.id.textview);
        copyText = (Button) findViewById(R.id.bCopy);
        copyText.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                String getstring = textView.getText().toString();

                //Help to continue :)

            }
        });
    }

}

I want to copy the Text in TextView textView to clipboard when the Button bCopy is pressed.

Answer

stinepike picture stinepike · Oct 8, 2013

use ClipboardManager

 ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
 ClipData clip = ClipData.newPlainText(label, text);
 clipboard.setPrimaryClip(clip);

make sure you have imported android.content.ClipboardManager and NOT android.text.ClipboardManager. Latter is deprecated. Check this link for Further information.