在 Jetpack Compose 中,我想处理 TextField 中的多个 imeAction 事件。我想要回车键创建一个新行并移动到其他文本字段。在许多应用程序中,这显示在长按 Enter 键时出现的小菜单中。
由于imeAction参数只能传递一个,所以keyboardActions中的操作不起作用。
@Composable
fun MainScreen() {
var tf1 by remember { mutableStateOf("") }
var text by remember { mutableStateOf("") }
var tf2 by remember { mutableStateOf("") }
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp,Alignment.CenterVertically)
) {
TextField(value = tf1, onValueChange = {tf1 = it})
TextField(
value = text,
onValueChange = { text = it },
keyboardOptions =
KeyboardOptions(
// I want to use Default, Previous and Next imeActions in this TextField.
imeAction = ImeAction.Default,
),
singleLine = false,
keyboardActions = KeyboardActions(
onPrevious = {
defaultKeyboardAction(
ImeAction.Previous
)
},
onNext = {
defaultKeyboardAction(
ImeAction.Next
)
}
)
)
TextField(value = tf2, onValueChange = {tf2 = it})
}
}
在 Jetpack Compose 中,在单个 TextField 中处理多个 ImeAction 事件具有挑战性,因为一次只能设置一个 imeAction。为了支持移动到其他文本字段(使用“下一个”或“上一个”操作)和添加新行,您可以通过自定义基于 Enter 键的行为并手动实现导航逻辑来解决此问题。
您可以通过检查文本字段中的特定按键事件(例如 Enter 键),然后使用条件操作来创建新行或移至下一个/上一个字段来实现此目的。您可以这样做:
@Composable
fun MainScreen() {
var tf1 by remember { mutableStateOf("") }
var text by remember { mutableStateOf("") }
var tf2 by remember { mutableStateOf("") }
val focusRequester1 = FocusRequester()
val focusRequester2 = FocusRequester()
val focusRequester3 = FocusRequester()
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically)
) {
TextField(
value = tf1,
onValueChange = { tf1 = it },
modifier = Modifier.focusRequester(focusRequester1),
keyboardOptions = KeyboardOptions.Default,
keyboardActions = KeyboardActions(
onNext = { focusRequester2.requestFocus() }
)
)
TextField(
value = text,
onValueChange = { text = it },
modifier = Modifier
.focusRequester(focusRequester2)
.onKeyEvent { event ->
if (event.key == Key.Enter && event.type == KeyEventType.KeyUp) {
focusRequester3.requestFocus()
true
} else {
false
}
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Default),
singleLine = false,
)
TextField(
value = tf2,
onValueChange = { tf2 = it },
modifier = Modifier.focusRequester(focusRequester3),
keyboardOptions = KeyboardOptions.Default,
keyboardActions = KeyboardActions(
onPrevious = { focusRequester2.requestFocus() }
)
)
}
}