以使用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")
}
}
可以创建将文本复制到剪贴板的函数。我做了这个:
fun copyToClipboard(context: Context, text: String) {
val clipboardManager =
context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("password", text)
clipboardManager.setPrimaryClip(clip)
}
密码标签是因为我用它来复制密码,但您应该将其替换为表示您正在复制内容的标签。
获取可在包含视图的模块中使用的上下文。例如,我有一个 Button 来调用模块中的函数,因此我将上下文传递给它。LocalContext.currentcopyToClipboardTopContent
@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)
}
}
}
}
如果您遇到问题,请确保导入这些库:
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context