Jetpack Compose OutlinedTextField gets focus but, no keyboard show up
Asked Answered
S

1

3

I want to show a dialog and automatically set focus to a OutlinedTextField, so user can instantly start typing.
I ended up with text field does get focus, does get the cursor flickering, but the keyboard remains hidden. So user still has to click on a textField to make the keyboard appear. Here is how I'm doing this

    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }

OutlinedTextField(
                        value = text,
                        modifier = Modifier
                            .focusRequester(focusRequester)
                            .fillMaxWidth(),
                        onValueChange = {
                            text = it
                        }
                    )
Stay answered 28/6, 2022 at 8:52 Comment(2)
Are you using an AlertDialog?Octan
@GabrieleMariotti yes, it's all inside a dialog, the composable name is "Dialog"Stay
S
5

To make keyboard show up, you should place a delay before requesting the focus:

LaunchedEffect(Unit) {
    delay(200)// <-- This is crucial.
    focusRequester.requestFocus()
}

OutlinedTextField(
    value = text,
    modifier = Modifier
        .focusRequester(focusRequester)
        .fillMaxWidth(),
    onValueChange = {
        text = it
    }
)

The delay time may be changed. For me it starts working starting from 100ms. If it still doesn't work with 200, increase it until it works. I believe it's all about performance of the devcie, so the higher the delay, the more slow devices can be used.

Stay answered 28/6, 2022 at 8:52 Comment(2)
How do you folks make the code more structured when pasting it from IDE?Stay
You can use shift+tab on Android Studio to align your code snippet to left then copy it, and paste it here.Rosemare

© 2022 - 2024 — McMap. All rights reserved.