Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Copying Text and Getting Text from the Clipboard

Author: Rachee Singh
Published? true -- FormatLanguage: W

Problem:

You need to copy text to the clipboard and access the text stored on the clipboard

Solution:

With the help of the ClipboardManager class, we can access the items stored on the clipboard of an Android device

Discussion:

ClipboardManager class allows us to copy text to the clipboard using the setText method and also allows us to get the text stored on the clipboard using the getText method. getText returns a charSequence which is converted to a String by the toString() method.

Here is a sample code, demonstrating how to obtain an instance of the ClipboardManager class and using it to copy text to the clipboard. Then the getText method is used to get the text on the clipboard and the text is set to a TextView.

ClipboardManager clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipboard.setText("Using the clipboard for the first time!");
String clip =  clipboard.getText().toString();
clipTextView = (TextView) findViewById(R.id.clipText);
clipTextView.setText(clip);
No records found.