Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
)
like image 277
Anudeep Ananth Avatar asked Dec 06 '25 08:12

Anudeep Ananth


2 Answers

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()
}
like image 102
Gabriele Mariotti Avatar answered Dec 08 '25 21:12

Gabriele Mariotti


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)
)
like image 27
Vicky Avatar answered Dec 08 '25 21:12

Vicky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!