10

I want the keyboard to pop up by an auto requesting focus on a text field in jetpack compose when the user navigates to a composable. As of now, this is what I have tried but it doesn't seem to work

val feedbackContent = remember { mutableStateOf(TextFieldValue()) }
val focusRequester = remember { FocusRequester() }

OutlinedTextField(
                modifier = Modifier
                    .clickable {
                        focusRequester.requestFocus()
                    }
                    .fillMaxWidth()
                    .focusRequester(focusRequester)
                    .focusable()
)
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Anudeep Ananth
  • 955
  • 1
  • 8
  • 30

1 Answers1

6

You can use something like:

val focusRequester = remember { FocusRequester() }
val keyboardController = LocalSoftwareKeyboardController.current

OutlinedTextField(
    value = text,
    onValueChange = { text = it},
    modifier = Modifier
        .fillMaxWidth()
        .focusRequester(focusRequester)
        .onFocusChanged {
            if (it.isFocused) {
                keyboardController?.show()
            }
        }
)

LaunchedEffect(Unit) {
    focusRequester.requestFocus()
}
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
  • 2
    Hi @Gabriele I also tried your another answer, however neither of them seem to be working. I can definite see that the outlinedText is getting focused, however the keyboard is not showing nor there is a cursor inside. Is there anything else need to be done to achieve OP's effect? Many thanks. – dumbfingers Jul 16 '21 at 15:54
  • 10
    @GabrieleMariotti, is there a reason to use `DisposableEffect` in case `onDispose{}` isn't actually needed? Will `LaunchedEffect` be sufficient in those cases? – azizbekian Jul 19 '21 at 08:55
  • 1
    this does not work – Waldmann Jun 28 '22 at 08:11
  • should use it.hasFocus instead of isFocused. Atleast that is what worked for me. – Syed Zeeshan Jun 22 '23 at 12:33