Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close the virtual keyboard from a Jetpack Compose TextField?

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 } ) 
like image 232
nglauber Avatar asked Dec 02 '19 05:12

nglauber


People also ask

How to hide Keyboard in jetpack compose?

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.

How do I close the Keyboard on Android?

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.

How do I get TextField value in jetpack compose?

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.


1 Answers

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.

like image 146
Gabriele Mariotti Avatar answered Sep 22 '22 14:09

Gabriele Mariotti