How to auto request focus to a text field when navigated to a composable in jetpack compose
Asked Answered
D

2

16

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()
)
Denunciation answered 6/7, 2021 at 10:7 Comment(0)
A
19

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()
}
Affair answered 6/7, 2021 at 11:0 Comment(4)
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.Alitaalitha
@GabrieleMariotti, is there a reason to use DisposableEffect in case onDispose{} isn't actually needed? Will LaunchedEffect be sufficient in those cases?Retha
this does not workPlatinous
should use it.hasFocus instead of isFocused. Atleast that is what worked for me.Advertisement
K
2

I believe you can try this (I tested this, and it works):

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

LaunchedEffect(Unit) {
    focusRequester.requestFocus()
}

OutlinedTextField(
    value = text,
    onValueChange = { text = it },
    modifier = Modifier
        .fillMaxWidth()
        .focusRequester(focusRequester)
)
Krill answered 15/2 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.