12

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Shadab Saif
  • 121
  • 1
  • 5
  • Does this answer your question: [How to Copy Text to Clip Board in Android?](https://stackoverflow.com/questions/19253786/how-to-copy-text-to-clip-board-in-android) – Sambhav Khandelwal Apr 24 '22 at 07:39
  • Does this answer your question? [How to Copy Text to Clip Board in Android?](https://stackoverflow.com/questions/19253786/how-to-copy-text-to-clip-board-in-android) – nglauber Apr 26 '22 at 18:03

2 Answers2

27

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")
    }
}
Thracian
  • 43,021
  • 16
  • 133
  • 222
3

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!