The Android Clipboard Framework is a powerful tool for handling the copy-paste operations in Android. It provides a simple way to transfer textual data into and out of your app. In this blog, we will learn how to use the Clipboard Framework in an Android app using Java.
Accessing the Clipboard
To access the clipboard, you need to get the system service CLIPBOARD_SERVICE. Here’s how you can do it:
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
Copying Text to Clipboard
To copy text to the clipboard, you need to create a ClipData object and set it to the clipboard. Here’s how you can do it:
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);
In the above code, “label” is a label for the clip, and “Text to copy” is the actual text that you want to copy to the clipboard.
Pasting Text from Clipboard
To paste text from the clipboard, you need to get the primary clip and extract the text from it. Here’s how you can do it:
ClipData clip = clipboard.getPrimaryClip();
if (clip != null) {
ClipData.Item item = clip.getItemAt(0);
String text = item.getText().toString();
}
In the above code, we first check if there is a primary clip. If there is, we get the first item from the clip and extract the text from it.