我有一个文本字段,我想在其中监听 newLine(Enter) 并执行相应的操作。 我没有找到任何用于此特定目的的专用操作按钮。
我尝试使用 onKeyEvent 但发现这仅适用于硬件键盘。但是,它确实监听了 Key.Backspace 但没有监听 Key.Enter
OutlinedTextField(
modifier = Modifier
.onKeyEvent { // For hardware keyboard
if (it.key == Key.Enter) {
if (text.isNotBlank()) {
showCheckListTitle = true
viewModel.addListItem(index + 1, "")
}
},
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Text
),
keyboardActions = KeyboardActions(onAny = {
// Could not get it listened
Log.d("ListenToEnter", this.toString())
})
当使用其他 imeAction 如 ImeAction.Default 时,我无法执行任何键盘操作,也无法使用 onAny 进行监听(如上面的代码所示)。
其他操作(例如“完成”、“下一个”、“上一个”、“发送”、“搜索”)不符合目的,因为它不会在 imeAction 按钮中显示 Enter。
我想要实现的是,我想监听文本字段中的输入/新行,以便我可以执行相应的操作。
用户在文本字段中输入一些文本,按下软件键盘中的
Enter
键或Done
后,我们执行一些操作并清除文本字段的焦点。
val focusManager = LocalFocusManager.current
OutlinedTextField(
value = text,
onValueChange = {
text = it.replace("\n", "")
},
// preventing \n or enter key from the keyboard
singleLine = true,
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(
onDone = {
// perform some action
focusManager.clearFocus()
}
),
modifier = Modifier
.onKeyEvent { event -> // For hardware keyboard
if (event.key == Key.Enter) {
if (text.isNotBlank()) {
// perform some action
focusManager.clearFocus()
// to stop propagation of this event.
return@onKeyEvent true
}
}
return@onKeyEvent false
}
)
我希望你能理解我的英语:)