How to copy text programmatically in my Android app?

AndroidMenuClipboardmanager

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

Use ClipboardManager#setPrimaryClip method:

import android.content.ClipboardManager;

// ...

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

ClipboardManager API reference

Solution 2 - Android

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" />

Solution 3 - Android

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

Solution 4 - Android

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..

Solution 5 - Android

#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.

Solution 6 - Android

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());
        }
    }
}

Solution 7 - Android

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;

Solution 8 - Android

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.

Solution 9 - Android

@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;

Solution 10 - Android

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)

}

Solution 11 - Android

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)

Solution 12 - Android

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);

    }
}

Solution 13 - Android

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

Solution 14 - Android

I use this(work with fragments)- kotlinish way

  private fun copyTextToClipboard(copyText: String) {

        val clipboardManager = requireActivity().
                               getSystemService(CLIPBOARD_SERVICE) as 
                                       android.content.ClipboardManager

        val clipData = ClipData.newPlainText("userLabel" ,copyText.trim())

        clipboardManager.setPrimaryClip(clipData)

    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZachView Question on Stackoverflow
Solution 1 - AndroidFlySwatView Answer on Stackoverflow
Solution 2 - AndroidWarpzitView Answer on Stackoverflow
Solution 3 - AndroidViachaslau TysianchukView Answer on Stackoverflow
Solution 4 - AndroidayrinaView Answer on Stackoverflow
Solution 5 - AndroidSuragchView Answer on Stackoverflow
Solution 6 - Androidlive-loveView Answer on Stackoverflow
Solution 7 - AndroidMor2View Answer on Stackoverflow
Solution 8 - AndroidKing of MassesView Answer on Stackoverflow
Solution 9 - AndroidAgna JirKon RxView Answer on Stackoverflow
Solution 10 - AndroidVijayakumar GView Answer on Stackoverflow
Solution 11 - AndroidRajeev ShettyView Answer on Stackoverflow
Solution 12 - AndroidMehul BoghraView Answer on Stackoverflow
Solution 13 - AndroidJunsu LeeView Answer on Stackoverflow
Solution 14 - Androidjafar_amlView Answer on Stackoverflow