How to copy and paste data from clipboard in Android Android 02.03.2020

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.

Some important points about Android's clipboard:

  • The clipboard holds only one clip object at a time. When an application puts a clip object on the clipboard, the previous clip object disappears.
  • Clip object also contains Metadata, which has what MIME type or types are available. This Metadata helps you handle data.

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.

var myClipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager?

Copying data. The next thing you need to do is to instantiate the ClipData object by calling the respective type of data method of the ClipData class. In case of text data, the newPlainText method will be called. After that you have to set that data as the clip of the Clipboard Manager object.

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

Pasting data. In order to paste the data, we will first get the clip by calling the getPrimaryClip() method. And from that click we will get the item in ClipData.Item object. And from the object we will get the data.

val clipData = myClipboard?.primaryClip
val item = clipData?.getItemAt(0)
val text = item?.text.toString().trim()

Set clipboard primary clip change listener.

myClipboard?.addPrimaryClipChangedListener {
    val textToPaste:String = myClipboard?.primaryClip?.getItemAt(0)?.text.toString().trim()
    textInputEditText.setText(textToPaste)
}