DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Clipboard Operations in Android: Copy, Paste, and Rich Text Support

Clipboard Operations in Android: Copy, Paste, and Rich Text Support

The ClipboardManager API allows you to implement copy and paste functionality with support for rich text formats.

Basic Copy/Paste with ClipboardManager

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

// Copy text
val clip = ClipData.newPlainText("label", "text to copy")
clipboard.setPrimaryClip(clip)

// Paste text
val primaryClip = clipboard.primaryClip
val pastedText = primaryClip?.getItemAt(0)?.text
Enter fullscreen mode Exit fullscreen mode

Rich Text Support

For HTML or styled text:

val htmlClip = ClipData.newHtmlText("label", "plain text", "<b>HTML text</b>")
clipboard.setPrimaryClip(htmlClip)
Enter fullscreen mode Exit fullscreen mode

Compose Integration

val clipboardManager = LocalClipboardManager.current
Button(
    onClick = {
        clipboardManager.setText(AnnotatedString("Copy this!"))
    }
) {
    Text("Copy")
}
Enter fullscreen mode Exit fullscreen mode

Listening for Changes

Monitor clipboard changes with OnPrimaryClipChangedListener:

clipboard.addPrimaryClipChangedListener {
    val newClip = clipboard.primaryClip?.getItemAt(0)?.text
}
Enter fullscreen mode Exit fullscreen mode

Clipboard operations are essential for creating user-friendly apps that follow Android conventions. Rich text support enables more sophisticated content sharing.


8 Android app templates available on Gumroad

Top comments (0)