如何从 OutlinedTextField 捕获离开事件以关闭键盘?
fun LabelName(nameUpdate: String = "", name: (String) -> Unit) {
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.padding(end = 20.dp),
value = nameUpdate,
onValueChange = {
name(manageLength(it))
},
label = {
Text(text = stringResource(id = if ( nameUpdate.isNotEmpty() ) R.string.name else R.string.add_new_name))
}
}
But then I click on the button, OutlinedTextField stayed focusable
如果您只想隐藏键盘,则仅使用
keyboardController
。我还建议将键盘按钮更改为“完成”,就像我在下面的示例中所做的那样。而如果你想关闭焦点,则需要添加 LocalFocusManager
,这样按下手机键盘上的完成按钮后,焦点就会立即设置为 OutlinedTextField
。
val keyboardController = LocalSoftwareKeyboardController.current
val focusRequesterManager = LocalFocusManager.current
Column {
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.padding(end = 20.dp),
value = nameUpdate,
onValueChange = {
name(manageLength(it))
},
label = {
Text(text = stringResource(id = if ( nameUpdate.isNotEmpty() ) R.string.name else R.string.add_new_name))
},
keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(
onDone = {
keyboardController?.hide()
focusRequesterManager.clearFocus()
}
)
)
}