Publicado en Sin categoría

Uso del portapapeles en Android


import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.widget.Toast;

import com.webserveis.basewebtool.R;

import androidx.annotation.Nullable;

public class ClipboardUtils {

    public static String getClipboardText(final Context context) {
        final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        final ClipData clipData = clipboard.getPrimaryClip();
        if (clipData != null && clipData.getItemCount() > 0) {
            final CharSequence clipboardText = clipData.getItemAt(0).getText();
            if (clipboardText != null) {
                return clipboardText.toString();
            }
        }
        return null;
    }

    public static void setClipboardText(final Context context, @Nullable final String label, @Nullable final String text) {
        final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        final ClipData clipData = ClipData.newPlainText(label, text);
        clipboard.setPrimaryClip(clipData);
    }

    public static void setClipboardText(final Context context, @Nullable final String label, @Nullable final String text, boolean notify) {
        setClipboardText(context, label, text);
        if (notify) {
            Toast.makeText(context, String.format(context.getText(R.string.clipboard_copy).toString(), label), Toast.LENGTH_SHORT).show();
        }
    }
}

Git Clipboard Utils for Java Android