Clipboard framework in android

Android provides the clipboard framework for copying and pasting different types of data. The data could be text, images, binary stream data or other complex data types.

Android provides the library of ClipboardManager and ClipData and ClipData.item to use the copying and pasting framework.In order to use clipboard framework, you need to put data into clip object, and then put that object into system wide clipboard.

In order to use clipboard , you need to instantiate an object of ClipboardManager by calling the getSystemService() method. Its syntax is given below −

ClipboardManager myClipboard;
myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);

Copying data

ClipData myClip;
String text = "hello world";
myClip = ClipData.newPlainText("text", text);
myClipboard.setPrimaryClip(myClip);

The ClipData object can take these three form and following functions are used to create those forms.

Sr.No ClipData Form & Method
1

Text

newPlainText(label, text)

Returns a ClipData object whose single ClipData.Item object contains a text string.

2

URI

newUri(resolver, label, URI)

Returns a ClipData object whose single ClipData.Item object contains a URI.

3

Intent

newIntent(label, intent)

Returns a ClipData object whose single ClipData.Item object contains an Intent.

Pasting data

ClipData abc = myClipboard.getPrimaryClip();
ClipData.Item item = abc.getItemAt(0);
String text = item.getText().toString();

Apart from the these methods , there are other methods provided by the ClipboardManager class for managing clipboard framework. These methods are listed below −

Sr.No Method & description
1

getPrimaryClip()

This method just returns the current primary clip on the clipboard

2

getPrimaryClipDescription()

This method returns a description of the current primary clip on the clipboard but not a copy of its data.

3

hasPrimaryClip()

This method returns true if there is currently a primary clip on the clipboard

4

setPrimaryClip(ClipData clip)

This method sets the current primary clip on the clipboard

5

setText(CharSequence text)

This method can be directly used to copy text into the clipboard

6

getText()

This method can be directly used to get the copied text from the clipboard