Hide and Show Virtual Keyboard in Jetpack Compose

Hide and Show Virtual Keyboard in Jetpack Compose

This article is a short one and it aim is to show how to hide and show the virtual keyboard in jetpack compose…

If you're new to Jetpack Compose, i'll advise you take a look at the official documentation.

developer.android.com/jetpack/compose/menta..

Creating the UI

Our UI will be just a simple UI that consist of just two buttons which their functions is to show and hide the keyboard.

@ExperimentalComposeUiApi
@Composable
fun ShowKeyboard() {
    val keyboardController = LocalSoftwareKeyboardController.current
    var value by remember { mutableStateOf("") }

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center
    ) {

        TextField(
            value = value,
            onValueChange = { value = it },
            modifier = Modifier
                .padding(8.dp)
                .fillMaxWidth(),
        )
        Spacer(modifier = Modifier.height(12.dp))
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceEvenly

        ) {

            //show keyboard
            Button(
                onClick = {
                    keyboardController?.show()
                }
            ) {
                Text(text = "Show")
            }
            //hide keyboard
            Button(
                onClick = { keyboardController?.hide() }
            ) {
                Text(text = "Hide")
            }
        }
    }

the keyboard controller is the mastermind that does all the heavy lifting.

You have to include the @ExperimentalComposeUiApi at the top of the composable function up to the last parent.