How to copy text to clipboard in android

Here is the example to copy and paste text to and from android app.

Using ClipBoardManager class  ( Note:  use android.content.ClipboardManager to provide support for SDK > 11 and use android.text.ClipboardManager for SDK < 11. But it is now deprecated.

There are no any special permission are required to copy and paste content. You can copy content from your app and paste it to any app in your device.

Let’s first design our layout to copy contents on Copy Button click from EditText and paste it the TextView on another Paste Button Click.

Let’ s start with activity_main.xml file.

Now continue to code. 

On copy button click get object of ClipboardManager from system service by providing the Service Name. Here we want to Clipboard service so, pass Context.CLIPBOARD_SERVICE as a parameter in getSystemService method. 

Next ClipData that holds text from EdiText and set as primary clip of ClipboardManager.

On paste button click we use same system service and get object of ClipboardManager. and we get text from primary clip which we have set on copy button click. Index 0 is to get last copied item from ClipBoard.

Below is the MainActivity.kt file.

That’s It. Now run application and we finally get below output. 

Leave a Comment

Your email address will not be published. Required fields are marked *