Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use clipboard service in jetpack compose

I want to copy a string to the user's mobile clipboard but I don't have any idea how I can use clipboard services in jetpack compose, If there is any alternative or any method that we can use to copy text to clipboard please share.

like image 829
Shadab Saif Avatar asked Sep 09 '25 17:09

Shadab Saif


2 Answers

You can set and get text using LocalClipboardManager

val clipboardManager: ClipboardManager = LocalClipboardManager.current
var text by remember { mutableStateOf("")}

Column(modifier = Modifier.fillMaxSize()) {

    TextField(value = text, onValueChange = {text = it})
    Button(onClick = {
        clipboardManager.setText(AnnotatedString((text)))
    }) {
        Text("Copy")
    }

    Button(onClick = {
      clipboardManager.getText()?.text?.let {
          text = it
      }
    }) {
        Text("Get")
    }
}
like image 177
Thracian Avatar answered Sep 13 '25 07:09

Thracian


You can create a function to copy text to the clipboard. I made this:

fun copyToClipboard(context: Context, text: String) {
    val clipboardManager =
        context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val clip = ClipData.newPlainText("password", text)
    clipboardManager.setPrimaryClip(clip)
}

The password label is because I used it to copy a password, but you should replace it with a label that represents what you're copying.

To get the context you can use LocalContext.current in the module that contains the views. For example, I have a button to that calls the copyToClipboard function within the TopContent module, so I pass the context to it.

@Composable
fun MyApp() {
    val myOptions = getOptions(titles = listOf("Capital letters", "Numbers", "Symbols"))
    val mySlider = getSliderInfo()
    val myPassword = getPassword()
    val context = LocalContext.current

    Column {
        MyTitle()
        Box(modifier = Modifier.padding(25.dp)) {
            Column(
                modifier = Modifier.fillMaxSize(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.SpaceBetween
            ) {
                TopContent(options = myOptions, slider = mySlider, myPassword, context)
                GenerateButton(options = myOptions, slider = mySlider, myPassword)
            }
        }
    }
}

If you have problems, make sure you're importing this libraries:

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context

You can also read an article where this is better explained here!

like image 21
Francisco Torres Avatar answered Sep 13 '25 09:09

Francisco Torres