[android] How to copy text programmatically in my Android app?

I'm building an Android app and I want to copy the text value of an EditText widget. It's possible for the user to press Menu+A then Menu+C to copy the value, but how would I do this programmatically?

This question is related to android menu clipboardmanager

The answer is


Here is my working code

/**
 * Method to code text in clip board
 *
 * @param context context
 * @param text    text what wan to copy in clipboard
 * @param label   label what want to copied
 */
public static void copyCodeInClipBoard(Context context, String text, String label) {
    if (context != null) {
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText(label, text);
        if (clipboard == null || clip == null)
            return;
        clipboard.setPrimaryClip(clip);

    }
}

@FlySwat already gave the correct answer, I am just sharing the complete answer:

Use ClipboardManager.setPrimaryClip (http://developer.android.com/reference/android/content/ClipboardManager.html) method:

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip); 

Where label is a User-visible label for the clip data and text is the actual text in the clip. According to official docs.

It is important to use this import:

import android.content.ClipboardManager;

Android support library update

As of Android Oreo, the support library only goes down to API 14. Most newer apps probably also have a min API of 14, and thus don't need to worry about the issues with API 11 mentioned in some of the other answers. A lot of the code can be cleaned up. (But see my edit history if you are still supporting lower versions.)

Copy

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", selectedText);
if (clipboard == null || clip == null) return;
clipboard.setPrimaryClip(clip);

Paste

I'm adding this code as a bonus, because copy/paste is usually done in pairs.

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
try {
    CharSequence text = clipboard.getPrimaryClip().getItemAt(0).getText();
} catch (Exception e) {
    return;
}

Notes

  • Be sure to import the android.content.ClipboardManager version rather than the old android.text.ClipboardManager. Same for ClipData.
  • If you aren't in an activity you can get the service with context.getSystemService().
  • I used a try/catch block for getting the paste text because multiple things can be null. You can check each one if you find that way more readable.

Googling brings you to android.content.ClipboardManager and you could decide, as I did, that Clipboard is not available on API < 11, because the documentation page says "Since: API Level 11".

There are actually two classes, second one extending the first - android.text.ClipboardManager and android.content.ClipboardManager.

android.text.ClipboardManager is existing since API 1, but it works only with text content.

android.content.ClipboardManager is the preferred way to work with clipboard, but it's not available on API Level < 11 (Honeycomb).

To get any of them you need the following code:

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

But for API < 11 you have to import android.text.ClipboardManager and for API >= 11 android.content.ClipboardManager


Unless your app is the default input method editor (IME) or is the app that currently has focus, your app cannot access clipboard data on Android 10 or higher. https://developer.android.com/about/versions/10/privacy/changes#clipboard-data


ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("label", "Text to copy");
if (clipboard == null || clip == null)
    return;
clipboard.setPrimaryClip(clip);

And import import android.content.ClipboardManager;


Android support library update

As of Android Oreo, the support library only goes down to API 14. Most newer apps probably also have a min API of 14, and thus don't need to worry about the issues with API 11 mentioned in some of the other answers. A lot of the code can be cleaned up. (But see my edit history if you are still supporting lower versions.)

Copy

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", selectedText);
if (clipboard == null || clip == null) return;
clipboard.setPrimaryClip(clip);

Paste

I'm adding this code as a bonus, because copy/paste is usually done in pairs.

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
try {
    CharSequence text = clipboard.getPrimaryClip().getItemAt(0).getText();
} catch (Exception e) {
    return;
}

Notes

  • Be sure to import the android.content.ClipboardManager version rather than the old android.text.ClipboardManager. Same for ClipData.
  • If you aren't in an activity you can get the service with context.getSystemService().
  • I used a try/catch block for getting the paste text because multiple things can be null. You can check each one if you find that way more readable.

To enable the standard copy/paste for TextView, U can choose one of the following:

Change in layout file: add below property to your TextView

android:textIsSelectable="true"

In your Java class write this line two set the grammatically.

myTextView.setTextIsSelectable(true);

And long press on the TextView you can see copy/paste action bar.


So everyone agree on how this should be done, but since no one want to give a complete solution, here goes:

int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setText("text to clip");
} else {
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
    android.content.ClipData clip = android.content.ClipData.newPlainText("text label","text to clip");
    clipboard.setPrimaryClip(clip);
}

I assume you have something like following declared in manifest:

<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="14" />

To enable the standard copy/paste for TextView, U can choose one of the following:

Change in layout file: add below property to your TextView

android:textIsSelectable="true"

In your Java class write this line two set the grammatically.

myTextView.setTextIsSelectable(true);

And long press on the TextView you can see copy/paste action bar.


Here is some code to implement some copy and paste functions from EditText (thanks to Warpzit for version check). You can hook these to your button's onclick event.

public void copy(View v) {      
    int startSelection = txtNotes.getSelectionStart();
    int endSelection = txtNotes.getSelectionEnd();      
    if ((txtNotes.getText() != null) && (endSelection > startSelection ))
    {
        String selectedText = txtNotes.getText().toString().substring(startSelection, endSelection);                
        int sdk = android.os.Build.VERSION.SDK_INT;
        if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            clipboard.setText(selectedText);
        } else {
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
            android.content.ClipData clip = android.content.ClipData.newPlainText("WordKeeper",selectedText);
            clipboard.setPrimaryClip(clip);
        }
    }
}   

public void paste(View v) {
    int sdk = android.os.Build.VERSION.SDK_INT;
    if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard.getText() != null) {
            txtNotes.getText().insert(txtNotes.getSelectionStart(), clipboard.getText());
        }
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
        if (item.getText() != null) {
            txtNotes.getText().insert(txtNotes.getSelectionStart(), item.getText());
        }
    }
}

Unless your app is the default input method editor (IME) or is the app that currently has focus, your app cannot access clipboard data on Android 10 or higher. https://developer.android.com/about/versions/10/privacy/changes#clipboard-data


For Kotlin, we can use the following method. You can paste this method inside an activity or fragment.

fun copyToClipBoard(context: Context, message: String) {

    val clipBoard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clipData = ClipData.newPlainText("label",message)
    clipBoard.setPrimaryClip(clipData)

}

@FlySwat already gave the correct answer, I am just sharing the complete answer:

Use ClipboardManager.setPrimaryClip (http://developer.android.com/reference/android/content/ClipboardManager.html) method:

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip); 

Where label is a User-visible label for the clip data and text is the actual text in the clip. According to official docs.

It is important to use this import:

import android.content.ClipboardManager;

For Kotlin use the below code inside the activity.

import android.content.ClipboardManager


 val clipBoard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
 val clipData = ClipData.newPlainText("label","Message to be Copied")
 clipBoard.setPrimaryClip(clipData)

For Kotlin, we can use the following method. You can paste this method inside an activity or fragment.

fun copyToClipBoard(context: Context, message: String) {

    val clipBoard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clipData = ClipData.newPlainText("label",message)
    clipBoard.setPrimaryClip(clipData)

}

For Kotlin use the below code inside the activity.

import android.content.ClipboardManager


 val clipBoard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
 val clipData = ClipData.newPlainText("label","Message to be Copied")
 clipBoard.setPrimaryClip(clipData)

So everyone agree on how this should be done, but since no one want to give a complete solution, here goes:

int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setText("text to clip");
} else {
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
    android.content.ClipData clip = android.content.ClipData.newPlainText("text label","text to clip");
    clipboard.setPrimaryClip(clip);
}

I assume you have something like following declared in manifest:

<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="14" />

Here is some code to implement some copy and paste functions from EditText (thanks to Warpzit for version check). You can hook these to your button's onclick event.

public void copy(View v) {      
    int startSelection = txtNotes.getSelectionStart();
    int endSelection = txtNotes.getSelectionEnd();      
    if ((txtNotes.getText() != null) && (endSelection > startSelection ))
    {
        String selectedText = txtNotes.getText().toString().substring(startSelection, endSelection);                
        int sdk = android.os.Build.VERSION.SDK_INT;
        if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            clipboard.setText(selectedText);
        } else {
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
            android.content.ClipData clip = android.content.ClipData.newPlainText("WordKeeper",selectedText);
            clipboard.setPrimaryClip(clip);
        }
    }
}   

public void paste(View v) {
    int sdk = android.os.Build.VERSION.SDK_INT;
    if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard.getText() != null) {
            txtNotes.getText().insert(txtNotes.getSelectionStart(), clipboard.getText());
        }
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
        if (item.getText() != null) {
            txtNotes.getText().insert(txtNotes.getSelectionStart(), item.getText());
        }
    }
}

Here is my working code

/**
 * Method to code text in clip board
 *
 * @param context context
 * @param text    text what wan to copy in clipboard
 * @param label   label what want to copied
 */
public static void copyCodeInClipBoard(Context context, String text, String label) {
    if (context != null) {
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText(label, text);
        if (clipboard == null || clip == null)
            return;
        clipboard.setPrimaryClip(clip);

    }
}

Googling brings you to android.content.ClipboardManager and you could decide, as I did, that Clipboard is not available on API < 11, because the documentation page says "Since: API Level 11".

There are actually two classes, second one extending the first - android.text.ClipboardManager and android.content.ClipboardManager.

android.text.ClipboardManager is existing since API 1, but it works only with text content.

android.content.ClipboardManager is the preferred way to work with clipboard, but it's not available on API Level < 11 (Honeycomb).

To get any of them you need the following code:

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

But for API < 11 you have to import android.text.ClipboardManager and for API >= 11 android.content.ClipboardManager


public void onClick (View v) 
{
    switch (v.getId())
    {
        case R.id.ButtonCopy:
            copyToClipBoard();
            break;
        case R.id.ButtonPaste:
            pasteFromClipBoard();
            break;
        default:
            Log.d(TAG, "OnClick: Unknown View Received!");
            break;
    }
}

// Copy EditCopy text to the ClipBoard
private void copyToClipBoard() 
{
    ClipboardManager clipMan = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    clipMan.setPrimaryClip(editCopy.getText());
}

you can try this..


ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("label", "Text to copy");
if (clipboard == null || clip == null)
    return;
clipboard.setPrimaryClip(clip);

And import import android.content.ClipboardManager;


public void onClick (View v) 
{
    switch (v.getId())
    {
        case R.id.ButtonCopy:
            copyToClipBoard();
            break;
        case R.id.ButtonPaste:
            pasteFromClipBoard();
            break;
        default:
            Log.d(TAG, "OnClick: Unknown View Received!");
            break;
    }
}

// Copy EditCopy text to the ClipBoard
private void copyToClipBoard() 
{
    ClipboardManager clipMan = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    clipMan.setPrimaryClip(editCopy.getText());
}

you can try this..