How to close the virtual keyboard from a Jetpack Compose TextField?
With the 1.0.x
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.currentTextField( value = text, onValueChange = { text = it }, label = { Text("Label") }, keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), keyboardActions = KeyboardActions( onDone = {keyboardController?.hide()}))
Starting from compose 1.0.0-alpha12
(and still valid in compose 1.0.4
) the onImeActionPerformed
is deprecated and suggested approach is to use keyboardActions
with combination of keyboardOptions
:
val focusManager = LocalFocusManager.current OutlinedTextField( value = ..., onValueChange = ..., label = ..., keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() }), keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done, keyboardType = KeyboardType.Password), )
focusManager.clearFocus()
will take care of dismissing the soft keyboard.
In 1.0.0
you can either use SoftwareKeyboardController
or FocusManager
to do this.
This answer focuses on their differences.
Setup:
var text by remember { mutableStateOf("")}TextField( value = text, onValueChange = { text = it }, keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), keyboardActions = KeyboardActions(onDone = { /* TODO */ }),)
SoftwareKeyboardController:
Based on @Gabriele Mariottis
answer.
val keyboardController = LocalSoftwareKeyboardController.current// TODO =keyboardController?.hide()
This only closes the keyboard, but does NOT clear the focus from any focused TextField (note the cursor & thick underline).
FocusManager:
Based on @azizbekians
answer.
val focusManager = LocalFocusManager.current// TODO =focusManager.clearFocus()
This closes the keyboard AND clears the focus from the TextField.