Copy a text to clipboard - Android android.content

Android examples for android.content:Clipboard

Description

Copy a text to clipboard

Demo Code

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;
import com.android.contacts.R;

public class Main{

    /**//from   w ww  .  j av  a2  s  .com
     * Copy a text to clipboard.
     *
     * @param context Context
     * @param label Label to show to the user describing this clip.
     * @param text Text to copy.
     * @param showToast If {@code true}, a toast is shown to the user.
     */
    public static void copyText(Context context, CharSequence label,
            CharSequence text, boolean showToast) {
        if (TextUtils.isEmpty(text))
            return;

        ClipboardManager clipboardManager = (ClipboardManager) context
                .getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText(label == null ? ""
                : label, text);
        clipboardManager.setPrimaryClip(clipData);

        if (showToast) {
            String toastText = context
                    .getString(R.string.toast_text_copied);
            Toast.makeText(context, toastText, Toast.LENGTH_SHORT).show();
        }
    }

}

Related Tutorials