453

Can anybody please tell me how to copy the text present in a particular textview to clipboard when a button is pressed?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainpage);
    textView = (TextView) findViewById(R.id.textview);
    copyText = (Button) findViewById(R.id.bCopy);
    copyText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            String getstring = textView.getText().toString();
            
            // Help to continue :)
        }
    });
}

I want to copy the Text in TextView textView to clipboard when the Button bCopy is pressed.

Darshan Gowda
  • 4,956
  • 3
  • 19
  • 27
  • 2
    Possible duplicate of [How to copy text programmatically in my Android app?](http://stackoverflow.com/questions/238284/how-to-copy-text-programmatically-in-my-android-app) – Shabbir Dhangot Jun 24 '16 at 07:43
  • https://stackoverflow.com/q/48791271/9274175 Please answer this questions on coppy – Yash Kale Feb 17 '18 at 20:37

32 Answers32

820

use ClipboardManager

 ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
 ClipData clip = ClipData.newPlainText(label, text);
 clipboard.setPrimaryClip(clip);

make sure you have imported android.content.ClipboardManager and NOT android.text.ClipboardManager. Latter is deprecated. Check this link for Further information.

Pang
  • 9,564
  • 146
  • 81
  • 122
stinepike
  • 54,068
  • 14
  • 92
  • 112
  • 5
    This is for API11+ only not working for GB and below – Javier Jan 14 '14 at 18:32
  • @zen I think you can use "setText" for GB. – android developer Dec 23 '14 at 08:40
  • import `android.content.ClipboardManager` and ***not*** `android.text.ClipboardManager` (I got `'android.text.ClipboardManager' is deprecated` warning) – Atul Jul 03 '16 at 08:38
  • 85
    What is the "label" used for? – android developer Jan 17 '17 at 08:31
  • @androiddeveloper - You can reference the definition of the method in ClipData.java: /*** Create a new ClipData holding data of the type * {link ClipDescription#MIMETYPE_TEXT_PLAIN}. * * param label User-visible label for the clip data. * param text The actual text in the clip. * return Returns a new ClipData containing the specified data. */ static public ClipData newPlainText(CharSequence label, CharSequence text) {... } In my case, I simply used "null" instead of "label". – David Roman Jan 24 '17 at 13:06
  • 32
    @androiddeveloper Explanation of the "label" parameter: https://stackoverflow.com/questions/33207809/what-exactly-is-label-parameter-in-clipdata-in-android – smg Jun 20 '17 at 22:27
  • 3
    @smg So it's more for developers? But how come it says it's shown for users? – android developer Jun 21 '17 at 16:15
  • I guess we'll never know – Denny Dec 21 '18 at 18:52
  • 22
    In androidx it actually becomes `ClipboardManager clipboard = getSystemService(getContext(), ClipboardManager.class);` – HoratioCain Apr 25 '19 at 18:30
93

Here the method to copy text to clipboard:

private void setClipboard(Context context, String text) {
  if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setText(text);
  } else {
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", text);
    clipboard.setPrimaryClip(clip);
  }
}

This method is working on all android devices.

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
vuhung3990
  • 6,353
  • 1
  • 45
  • 44
  • 2
    I don't understand what mean with "context". Can you add an example of how to properly call that method? Thanks. – E_Blue Nov 13 '16 at 20:51
  • hey guy, context is required in fragment to call getSystemService – vuhung3990 Jan 22 '17 at 05:46
  • @E_Blue context.getSystemService(Context.CLIPBOARD_SERVICE) ??? really??? – androidStud Dec 16 '19 at 02:49
  • 1
    @E_Blue looks like you are a naive android developer who's asking about context. Well that is also not a problem, but just mind your tone and do some study/research about things too. – androidStud Dec 16 '19 at 02:50
67

As a handy kotlin extension:

fun Context.copyToClipboard(text: CharSequence){
    val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clip = ClipData.newPlainText("label",text)
    clipboard.setPrimaryClip(clip)
}

Update:

If you using ContextCompat you should use:

ContextCompat.getSystemService(this, ClipboardManager::class.java)
crgarridos
  • 8,758
  • 3
  • 49
  • 61
61

Yesterday I made this class. Take it, it's for all API Levels

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.util.Log;
import de.lochmann.nsafirewall.R;

public class MyClipboardManager {

    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    public boolean copyToClipboard(Context context, String text) {
        try {
            int sdk = android.os.Build.VERSION.SDK_INT;
            if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
                        .getSystemService(context.CLIPBOARD_SERVICE);
                clipboard.setText(text);
            } else {
                android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
                        .getSystemService(context.CLIPBOARD_SERVICE);
                android.content.ClipData clip = android.content.ClipData
                        .newPlainText(
                                context.getResources().getString(
                                        R.string.message), text);
                clipboard.setPrimaryClip(clip);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @SuppressLint("NewApi")
    public String readFromClipboard(Context context) {
        int sdk = android.os.Build.VERSION.SDK_INT;
        if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
                    .getSystemService(context.CLIPBOARD_SERVICE);
            return clipboard.getText().toString();
        } else {
            ClipboardManager clipboard = (ClipboardManager) context
                    .getSystemService(Context.CLIPBOARD_SERVICE);

            // Gets a content resolver instance
            ContentResolver cr = context.getContentResolver();

            // Gets the clipboard data from the clipboard
            ClipData clip = clipboard.getPrimaryClip();
            if (clip != null) {

                String text = null;
                String title = null;

                // Gets the first item from the clipboard data
                ClipData.Item item = clip.getItemAt(0);

                // Tries to get the item's contents as a URI pointing to a note
                Uri uri = item.getUri();

                // If the contents of the clipboard wasn't a reference to a
                // note, then
                // this converts whatever it is to text.
                if (text == null) {
                    text = coerceToText(context, item).toString();
                }

                return text;
            }
        }
        return "";
    }

    @SuppressLint("NewApi")
    public CharSequence coerceToText(Context context, ClipData.Item item) {
        // If this Item has an explicit textual value, simply return that.
        CharSequence text = item.getText();
        if (text != null) {
            return text;
        }

        // If this Item has a URI value, try using that.
        Uri uri = item.getUri();
        if (uri != null) {

            // First see if the URI can be opened as a plain text stream
            // (of any sub-type). If so, this is the best textual
            // representation for it.
            FileInputStream stream = null;
            try {
                // Ask for a stream of the desired type.
                AssetFileDescriptor descr = context.getContentResolver()
                        .openTypedAssetFileDescriptor(uri, "text/*", null);
                stream = descr.createInputStream();
                InputStreamReader reader = new InputStreamReader(stream,
                        "UTF-8");

                // Got it... copy the stream into a local string and return it.
                StringBuilder builder = new StringBuilder(128);
                char[] buffer = new char[8192];
                int len;
                while ((len = reader.read(buffer)) > 0) {
                    builder.append(buffer, 0, len);
                }
                return builder.toString();

            } catch (FileNotFoundException e) {
                // Unable to open content URI as text... not really an
                // error, just something to ignore.

            } catch (IOException e) {
                // Something bad has happened.
                Log.w("ClippedData", "Failure loading text", e);
                return e.toString();

            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                    }
                }
            }

            // If we couldn't open the URI as a stream, then the URI itself
            // probably serves fairly well as a textual representation.
            return uri.toString();
        }

        // Finally, if all we have is an Intent, then we can just turn that
        // into text. Not the most user-friendly thing, but it's something.
        Intent intent = item.getIntent();
        if (intent != null) {
            return intent.toUri(Intent.URI_INTENT_SCHEME);
        }

        // Shouldn't get here, but just in case...
        return "";
    }

}
A.S.
  • 4,574
  • 3
  • 26
  • 43
  • What does "coerceToText" do? also, is it possible to copy/paste other types of data to the clipboard (example: bitmap) ? – android developer Dec 31 '14 at 23:38
  • 1
    @A.S. why you written corceToText method your self? ! its already available with api see https://developer.android.com/reference/android/content/ClipData.Item.html#coerceToText%28android.content.Context%29 – Hardik Aug 10 '16 at 08:10
  • But I think there is time for developers to stop supporting stuff before about API17. There aren't much units left of elder types and they do not tend to download new apps? For instance I use elder units for navigation in my sailboat, and everything else is wiped. I don't mind throwing such units over board by mistake? – Jan Bergström Mar 18 '19 at 22:12
42

For Jetpack Compose

val localClipboardManager = LocalClipboardManager.current
localClipboardManager.setText(AnnotatedString("Your text here"))
Thaw De Zin
  • 1,409
  • 2
  • 10
  • 18
15

Just use this. It works only for android api >= 11 before that you'll have to use a ClipData.

ClipboardManager _clipboard = (ClipboardManager) _activity.getSystemService(Context.CLIPBOARD_SERVICE);
_clipboard.setText(YOUR TEXT);

Hope it helped you :)

[UPDATE 3/19/2015] Just like Ujjwal Singh said it the method setText is deprecated now, you should use, just as the docs recommande it, setPrimaryClip(clipData)

Community
  • 1
  • 1
Ektos974
  • 999
  • 10
  • 30
14

This can be done in Kotlin like this:

var clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
var clip = ClipData.newPlainText("label", file.readText())
clipboard.setPrimaryClip = clip

Where file.readText() is your input string.

Nikhil Katekhaye
  • 2,344
  • 1
  • 18
  • 19
11

Kotlin extension function 2021:

fun Context.copyToClipboard(text: CharSequence){
    val clipboard = ContextCompat.getSystemService(this,ClipboardManager::class.java)
    clipboard?.setPrimaryClip(ClipData.newPlainText("",text))
}
Merthan Erdem
  • 5,598
  • 2
  • 22
  • 29
8

use this code

   private ClipboardManager myClipboard;
   private ClipData myClip;
   TextView textView;
   Button copyText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainpage);
    textView = (TextView) findViewById(R.id.textview);
    copyText = (Button) findViewById(R.id.bCopy);
    myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);

    copyText.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


           String text = textView.getText().toString();
           myClip = ClipData.newPlainText("text", text);
           myClipboard.setPrimaryClip(myClip);
           Toast.makeText(getApplicationContext(), "Text Copied", 
           Toast.LENGTH_SHORT).show(); 
        }
    });
}
SKG
  • 346
  • 4
  • 11
7

use this function for copy to clipboard

public void copyToClipboard(String copyText) {
    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(copyText);
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager)
                getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData
                .newPlainText("Your OTP", copyText);
        clipboard.setPrimaryClip(clip);
    }
    Toast toast = Toast.makeText(getApplicationContext(),
            "Your OTP is copied", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 50, 50);
    toast.show();
    //displayAlert("Your OTP is copied");
}
Vimal Gajera
  • 497
  • 3
  • 9
6
@SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
@SuppressWarnings("deprecation")
@TargetApi(11)
public void onClickCopy(View v) {   // User-defined onClick Listener
    int sdk_Version = android.os.Build.VERSION.SDK_INT;
    if(sdk_Version < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(textView.getText().toString());   // Assuming that you are copying the text from a TextView
        Toast.makeText(getApplicationContext(), "Copied to Clipboard!", Toast.LENGTH_SHORT).show();
    }
    else { 
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
        android.content.ClipData clip = android.content.ClipData.newPlainText("Text Label", textView.getText().toString());
        clipboard.setPrimaryClip(clip);
        Toast.makeText(getApplicationContext(), "Copied to Clipboard!", Toast.LENGTH_SHORT).show();
    }   
}
Himanshu Aggarwal
  • 1,803
  • 2
  • 24
  • 36
6

If you want to copy text from edittext So First Create Edittext

    EditText mResultEt = findViewById(R.id.resultEt);

then Create One Button on which after clicking we can copy these text

    ImageButton copyClipBoard = findViewById(R.id.btn_copy);

then use the listener of the button

Java

copyClipBoard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClipboardManager clipboardManager = (ClipboardManager)
                        getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText("nonsense_data",
                        mResultEt.getText().toString());
                clipboardManager.setPrimaryClip(clipData);
                Toast.makeText(MainActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
            }
        });

Kotlin

btn1.setOnClickListener{
            val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
            val clipData = ClipData.newPlainText(
                "nonsense_data",
                content_et.getText().toString()
            )
            clipboardManager.setPrimaryClip(clipData)
            Toast.makeText(this@MainActivity, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show()

        }

and make sure to import this

import android.content.ClipboardManager;

don't import this one

android.text.ClipboardManager
Rehan Khan
  • 1,031
  • 13
  • 10
  • Please update, that code sample only is intended for activities, calling this in a fragment you need: activity?.let { val clipboardManager = it.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager – David Jul 15 '22 at 07:00
4

use this method:

 ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
 ClipData clip = ClipData.newPlainText(label, text);
 clipboard.setPrimaryClip(clip);

at the place of setPrimaryClip we can also use the following methods:

void    clearPrimaryClip()

Clears any current primary clip on the clipboard.

ClipData    getPrimaryClip()

Returns the current primary clip on the clipboard.

ClipDescription getPrimaryClipDescription()

Returns a description of the current primary clip on the clipboard but not a copy of its data.

CharSequence    getText()

This method is deprecated. Use getPrimaryClip() instead. This retrieves the primary clip and tries to coerce it to a string.

boolean hasPrimaryClip()

Returns true if there is currently a primary clip on the clipboard.

Pradeep Kumar
  • 2,349
  • 1
  • 10
  • 18
4

Simple and Easy Android Using Java.

copytext.setOnClickListener(v -> {
            ClipboardManager myClipboard;
            myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
            ClipData myClip;
            String Text = "Hello World!";
            myClip = ClipData.newPlainText("text", Text);
            myClipboard.setPrimaryClip(myClip);

            Toast.makeText(this, "Copy", Toast.LENGTH_SHORT).show();
        });
3
 ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); 
 ClipData clip = ClipData.newPlainText(label, text);
 clipboard.setPrimaryClip(clip);
  • dont forget the context it could be defined in mContext right before.... Or just add MyActivity.this, getAcpplicationContext ... Still the same getApplicationContext.getSystemService – Francis Eyogo Aug 23 '20 at 15:57
3

With Jetpack Compose, it's really easy:

AmbientClipboardManager.current.setText(AnnotatedString("Copied Text"))
AnT
  • 801
  • 9
  • 9
3

Simplest Code in Kotlin-

val myClipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val myClip: ClipData = ClipData.newPlainText("Label", "text")
        myClipboard.setPrimaryClip(myClip)

Note: Make sure you have imported android.content.ClipboardManager and NOT android.text.ClipboardManager. Latter is deprecated.

2

int sdk = android.os.Build.VERSION.SDK_INT;

    if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) DetailView.this
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText("" + yourMessage.toString());
        Toast.makeText(AppCstVar.getAppContext(),
                "" + getResources().getString(R.string.txt_copiedtoclipboard),
                Toast.LENGTH_SHORT).show();
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) DetailView.this
                .getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData
                .newPlainText("message", "" + yourMessage.toString());
        clipboard.setPrimaryClip(clip);
        Toast.makeText(AppCstVar.getAppContext(),
                "" + getResources().getString(R.string.txt_copiedtoclipboard),
                Toast.LENGTH_SHORT).show();
    }
Pankaj Singh
  • 2,241
  • 2
  • 16
  • 16
2
    String stringYouExtracted = referraltxt.getText().toString();
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
    android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", stringYouExtracted);

clipboard.setPrimaryClip(clip);
        Toast.makeText(getActivity(), "Copy coupon code copied to clickboard!", Toast.LENGTH_SHORT).show();
Keshav Gera
  • 10,807
  • 1
  • 75
  • 53
2
    import android.content.ClipData
    import android.content.ClipboardManager
    import android.content.Context

    val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    clipboardManager.setPrimaryClip(ClipData.newPlainText("text","this is copied...paste it" ))
Clean Coder
  • 496
  • 5
  • 12
1

Simple Kotlin Extension Function for Copying Text to Clipboard

fun Context.copyToClipboard(clipLabel: String, text: CharSequence){
    val clipboard = ContextCompat.getSystemService(this, ClipboardManager::class.java)
    clipboard?.setPrimaryClip(ClipData.newPlainText(clipLabel, text))

    toast("Copied $clipLabel")
}
0

Try the following code. It will support the latest API:

ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                        if (clipboard.hasPrimaryClip()) {
                            android.content.ClipDescription description = clipboard.getPrimaryClipDescription();
                            android.content.ClipData data = clipboard.getPrimaryClip();
                            if (data != null && description != null && description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN))
                            {
                                String url= (String) clipboard.getText();
                                searchText.setText(url);
                                System.out.println("data="+data+"description="+description+"url="+url);
                            }}
TsTeaTime
  • 881
  • 1
  • 13
  • 34
0

Kotlin helper method to attach click to copy Texts on a TextView

Put this method somewhere in Util class. This method attach click listener on textview to Copy Content of textView to a clipText on click of that textView

/**
 * Param:  cliplabel, textview, context
 */
fun attachClickToCopyText(textView: TextView?, clipLabel: String, context: Context?) {
    if (textView != null && null != context) {
        textView.setOnClickListener {
            val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val clip = ClipData.newPlainText(clipLabel, textView!!.text)
            clipboard.primaryClip = clip
            Snackbar.make(textView,
                    "Copied $clipLabel", Snackbar.LENGTH_LONG).show()
        }
    }

}
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
0

You can perform this copy to clipboard function when onclick button event. so put these code lines inside your button onClickListerner

android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clipData = android.content.ClipData.newPlainText("Text Label", ViewPass.getText().toString());
clipboardManager.setPrimaryClip(clipData);
Toast.makeText(getApplicationContext(),"Copied from Clipboard!",Toast.LENGTH_SHORT).show();
Malith Ileperuma
  • 926
  • 11
  • 27
0

In Kotlin I have an extension for this

fun Context.copyToClipboard(text: String) {
  val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
  val clip =
    ClipData.newPlainText(getString(R.string.copy_clipboard_label, getString(R.string.app_name)),text)
  clipboard.setPrimaryClip(clip)
}
Salman Nazir
  • 2,759
  • 2
  • 28
  • 42
0

For copy any text in Android:

            TextView text = findViewById(R.id.text_id);
            ImageView icons = findViewById(R.id.copy_icon);

            icons.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clipData = ClipData.newPlainText("text whatever you want", text.getText().toString());
                    clipboardManager.setPrimaryClip(clipData);

                    Toast.makeText(context, "Text Copied", Toast.LENGTH_SHORT).show();
                }
            });
Papel
  • 541
  • 4
  • 7
0

to search clip board list first get the clipboard object like this :

private val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager

then check if there is any data in clip board by this function :

fun isClipboardContainsData() : Boolean{
        return when{
            !clipboard.hasPrimaryClip() -> false
            else -> true
        }
    }

then use this function to go through the clipboard object like below:

fun searchClipboard() : ClipData.Item? {
        return if (isClipboardContainsData()){

            val items = clipboard.primaryClip
            val clipboardSize = items?.itemCount ?: 0
            for (i in 0..clipboardSize) {
                val item = items?.getItemAt(i)
                return if (item != null){
                       return item
                }else
                    null
            }
            return null
        }else
            null

    }

here you can see that the searchClipboard Item will return an item of type ClipData.Item, the clipboard contains a list of ClipData.Item and if you go through implementation of clipboard this is what you will find about ClipData.Item:

public static class Item {
    final CharSequence mText;
    final String mHtmlText;
    final Intent mIntent;
    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
    Uri mUri;
}

so what you can hold in a clipboard item could be of type:

  1. CharSequence
  2. String
  3. Intent(this supports copying application shortcuts)
  4. Uri (for copying complex data from a content provider)
Bita Mirshafiee
  • 600
  • 8
  • 14
0

If you want to make it shorter use:

ClipData clip = ClipData.newPlainText(label, text);
((ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE)).setPrimaryClip(clip);
harveyhans
  • 459
  • 6
  • 12
0

==> Its too Easy to Copy Content on the click of View.

-> Store Text into String variable.

-> Make Variable of ClipboardManager

-> Make Variable of ClipData

-> must imported from the package as " android.content."

-> set clip into clipboard.setPrimaryclick.

-> done.

ex.

import android.content.ClipboardManager;

import android.content.ClipData;





    stringNodetxt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String stringNodeCopied= stringNodetxt.getText().toString();

            ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = android.content.ClipData.newPlainText("Copied", stringNodeCopied);

            clipboard.setPrimaryClip(clip);
            Toast.makeText(getBaseContext(), "copied to clipboard!", Toast.LENGTH_SHORT).show();
        }
    });
0

For Kotlin Just type this code inside your Button. This code working for Fragment class.

var myClipboard = getSystemService(requireContext(), ClipboardManager::class.java) as ClipboardManager
            val copyText = quotes//quotes is actual text(I want to copy) that is assign in copyText.
            val clip = ClipData.newPlainText("Copied",copyText)
            myClipboard.setPrimaryClip(clip)
            Toast.makeText(requireActivity(), "Copied", Toast.LENGTH_SHORT).show()
0

Safe cast (as?) approach in Kotlin:

(context.getSystemService(CLIPBOARD_SERVICE) as? ClipboardManager)?.let {
  val clipData = ClipData.newPlainText("Google", "https://google.com")
  it.setPrimaryClip(clipData)
}
Areeb Momin
  • 199
  • 4
  • 4
-2

Just write this code:

clipboard.setText(getstring);
Azametzin
  • 5,223
  • 12
  • 28
  • 46
raza raza
  • 27
  • 4