安卓 jetpack compose 我要实现一个文本输入框,点击按钮可以将剪贴板的内容追加到输入框,并且光标跟随 ,帮我写完整代码
时间: 2024-05-11 20:19:40 浏览: 10
好的,以下是可以实现你所描述要求的安卓 Jetpack Compose 代码:
```
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.*
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyEvent
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
@Composable
fun InputTextField() {
var textState by remember { mutableStateOf(TextFieldValue()) }
var textClipboard by remember { mutableStateOf("") }
TextField(
value = textState,
onValueChange = {
textState = it
},
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp, horizontal = 16.dp)
.focusObserver {
if (it == FocusState.Active) {
// 保持光标在结尾
textState = textState.copy(selection = TextRange(textState.text.length, textState.text.length))
}
},
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(onDone = {
// 隐藏软键盘
it.hideSoftwareKeyboard()
}),
trailingIcon = {
IconButton(onClick = {
// 将剪贴板的内容追加到输入框
if (textClipboard.isNotEmpty()) {
val newText = "${textState.text}${if (textState.text.isNotEmpty()) " " else ""}$textClipboard"
textState = TextFieldValue(
text = newText,
selection = TextRange(newText.length, newText.length)
)
}
}) {
Icon(
imageVector = Icons.Default.ContentPaste,
contentDescription = "Paste"
)
}
},
colors = TextFieldDefaults.textFieldColors(
backgroundColor = MaterialTheme.colors.surface
)
)
// 监听剪贴板
DisposableEffect(Unit) {
val clipboardManager = LocalClipboardManager.current
val clipboardManagerChangedListener = ClipboardManager.OnPrimaryClipChangedListener {
// 获取剪贴板的内容
val clipboardText = clipboardManager.primaryClip?.getItemAt(0)?.coerceToText(LocalContext.current)
if (!clipboardText.isNullOrBlank()) {
textClipboard = clipboardText.toString().trim()
}
}
clipboardManager.addPrimaryClipChangedListener(clipboardManagerChangedListener)
onDispose {
clipboardManager.removePrimaryClipChangedListener(clipboardManagerChangedListener)
}
}
}
```
希望这份代码能够对你有所帮助。