I'm using the Jetpack Compose TextField
and I want to close the virtual keyboard when the user press the the action button (imeActionPerformed
parameter).
val text = +state { "" } TextField( value = text.value, keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, onImeActionPerformed = { // TODO Close the virtual keyboard here <<< } onValueChange = { s -> text.value = s } )
With the hide & show requests on SoftwareKeyboardController we can control the visibility of a Keyboard. If we have TextField with keyboard ImeAction. Done, then we need to invoke hide() call in the callback of Keyboard actions.
HIDE_IMPLICIT_ONLY, 0); Here pass HIDE_IMPLICIT_ONLY at the position of showFlag and 0 at the position of hiddenFlag . It will forcefully close soft Keyboard.
To read value entered in TextField in Android Compose, declare a variable, and assign this variable the value in the TextField whenever there is a change in the value. The same process holds for reading value entered in OutlineTextField composable.
You can use the LocalSoftwareKeyboardController
class to control the current software keyboard and then use the hide
method:
var text by remember { mutableStateOf(TextFieldValue("Text")) } val keyboardController = LocalSoftwareKeyboardController.current TextField( value = text, onValueChange = { text = it }, label = { Text("Label") }, keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), keyboardActions = KeyboardActions( onDone = {keyboardController?.hide()}) )
This solution closes the keyboard without removing the focus from the current TextField
.
Just to highlight the difference with:
val focusManager = LocalFocusManager.current focusManager.clearFocus()
This code closes the keyboard removing the focus from the TextField.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With