<Jetpack Compose> How to show/hide keyboard inside AlertDialog?

Issue

Does anyone knows how can I show or hide the keyboard inside AlertDialog? The focusManager.clearFocus() doesn’t work inside AlertDialog. Same for textInputService?.hideSoftwareKeyboard() and softwareKeyboardController?.hide().

For example:

AlertDialog(
    onDismissRequest = {
        openDialog.value = false
    },
    text = {
        TextField(...)
    }
    buttons = {
        Button(
            modifier = Modifier.fillMaxWidth(),
            onClick = { focusManager.clearFocus() }
        ) {
            Text("Update")
        }
    }
)

Solution

The AlertDialog has its own LocalFocusManager as well as some other local constants.

Most likely you are capturing the LocalFocusManager outside of AlertDialog, instead you need to capture it inside:

buttons = {
    val focusManager = LocalFocusManager.current
    Button(
        modifier = Modifier.fillMaxWidth(),
        onClick = { focusManager.clearFocus() }
    ) {
        Text("Update")
    }
}

Answered By – Philip Dukhov

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published