Search code examples
android-jetpack-composeandroid-jetpackandroid-windowmanagerandroid-window

How to show keyboard with Jetpack Compose?


How can I slide in the keyboard? I tried:

val keyboardController: SoftwareKeyboardController? = LocalSoftwareKeyboardController.current
  keyboardController?.show()

But it does not work. What am I missing? Maybe some Manifest flags?


Solution

  • To show keyboard in Compose:

    val showKeyboard = remember { mutableStateOf(true) }
    val focusRequester = remember { FocusRequester() }
    val keyboard = LocalSoftwareKeyboardController.current
    
    OutlinedTextField(
        modifier = Modifier
                .fillMaxWidth()
                .focusRequester(focusRequester),
        value = value,
        textStyle = MaterialTheme.typography.body2,
        onValueChange = { onValueChange(it)},
        label = { Text(label) }
    )
    
    // LaunchedEffect prevents endless focus request
    LaunchedEffect(focusRequester) {
        if (showKeyboard.equals(true)) {
            focusRequester.requestFocus()
            delay(100) // Make sure you have delay here
            keyboard?.show()
        }
    }