web-dev-qa-db-fra.com

Comment copier du texte dans le presse-papiers sous Android?

Quelqu'un peut-il me dire s'il vous plaît comment copier le texte présent dans une vue de texte particulière dans le presse-papiers lorsqu'un bouton est enfoncé? Merci :)

@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 :)





        }
    });
}

}

Je veux copier le texte dans TextView textView dans le presse-papiers lorsque vous appuyez sur le bouton bCopy! S'il vous plaît, aidez ...

256
Darshan Gowda

utiliser ClipboardManager

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

assurez-vous que vous avez importé Android.content.ClipboardManager et NOT Android.text.ClipboardManager. Ce dernier est obsolète. Cochez cette lien pour plus d'informations.

477
stinepike

Voici la méthode pour copier du texte dans le presse papier:

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

Cette méthode fonctionne sur tous les appareils Android.

62
vuhung3990

Hier j'ai fait ce cours. Prenez-le, c'est pour tous les niveaux d'API

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 "";
    }

}
56
A.S.

Comme extension pratique de Kotlin:

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

Mise à jour:

Si vous utilisez ContextCompat, vous devez utiliser:

ContextCompat.getSystemService(this, ClipboardManager::class.Java)
13
crgarridos

Il suffit d'utiliser ceci. Cela ne fonctionne que pour Android api> = 11 avant que vous deviez utiliser un ClipData.

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

J'espère que ça vous a aidé :)

[UPDATE 3/19/2015] Tout comme jjwal Singh l'a dit, la méthode setText est obsolète maintenant, vous devriez utiliser, comme le recommande la documentation, setPrimaryClip (clipData)

12
Ektos974

Cela peut être fait à Kotlin comme ceci:

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

file.readText() est votre chaîne d'entrée.

7
Nikhil Katekhaye

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

utiliser cette fonction pour copier dans le presse papier

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");
}
6
Vimal Gajera
@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();
    }   
}
6
Himanshu Aggarwal

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();
    }
0
Pankaj Singh
    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();
0
Keshav Gera

Essayez le code suivant. Il supportera la dernière 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);
                            }}
0
Ranjith Guru