androidkotlinandroid-jetpack-composeandroid-input-methodandroid-compose-textfield

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 }
)

Solution

  • Starting from compose 1.0.0-alpha12 (and still valid in compose 1.6.8) 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.