Skip to content
DeveloperMemos

Using Jetpack Compose's LocalClipboardManager

Jetpack Compose, LocalClipboardManager, Android Development1 min read

Jetpack Compose is a modern toolkit for building native Android UI. One of the features it provides is the LocalClipboardManager, which allows you to interact with the system clipboard.

Using LocalClipboardManager

To use LocalClipboardManager, you first need to obtain an instance of it. This can be done by calling LocalClipboardManager.current within a @Composable function.

Here is an example that shows how to copy text to the clipboard:

1@Composable
2fun CopyToClipboardExample() {
3 val clipboardManager = LocalClipboardManager.current
4 val text = remember { mutableStateOf("") }
5
6 Column {
7 TextField(
8 value = text.value,
9 onValueChange = { text.value = it },
10 label = { Text("Text to copy") }
11 )
12 Button(onClick = { clipboardManager.setText(AnnotatedString(text.value)) }) {
13 Text("Copy to clipboard")
14 }
15 }
16}

In this example, we have a TextField that allows the user to enter some text. When the user clicks the "Copy to clipboard" button, the text is copied to the clipboard using clipboardManager.setText().

Pasting Using LocalClipboardManager

We can also paste text from the clipboard. Here is an example that shows how to do this:

1@Composable
2fun PasteFromClipboardExample() {
3 val clipboardManager = LocalClipboardManager.current
4 val text = remember { mutableStateOf("") }
5
6 Column {
7 Text(text = text.value)
8 Button(onClick = {
9 val clipData = clipboardManager.getText()
10 if (clipData != null) {
11 text.value = clipData.text
12 }
13 }) {
14 Text("Paste from clipboard")
15 }
16 }
17}

In this example, we have a Text composable that displays the current value of text. When the user clicks the "Paste from clipboard" button, we call clipboardManager.getText() to get the current contents of the clipboard. If it is not null, we update the value of text with the contents of the clipboard.

Conclusion

Jetpack Compose's LocalClipboardManager provides an easy way to interact with the system clipboard on Android. You can use it to copy and paste text, as shown in the examples above.