在 OutlinedTextField 上留下事件

问题描述 投票:0回答:1

如何从 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 
keyboard android-jetpack-compose outlined-text-fields
1个回答
1
投票

如果您只想隐藏键盘,则仅使用

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()
            }
        )
    )
}
© www.soinside.com 2019 - 2024. All rights reserved.