Unit) { OutlinedTextField(" /> Unit) { OutlinedTextField(" /> Unit) { OutlinedTextField("/>

Leave event on OutlinedTextField

91 views Asked by At

How to catch leave event from OutlinedTextField to close keyboard?

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

1

There are 1 answers

0
Artur Andruszkiewicz On BEST ANSWER

If you only want to hide the keyboard then use keyboardController only. I also recommend changing the keyboard button to done, as I did in the example below. And if you want to turn off the focus, you need to add LocalFocusManager so that after pressing the done button on the keyboard on the phone, the focus will be immediately set to 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()
            }
        )
    )
}