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

Viewed 2249

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()
)
1 Answers

You can use something like:

val focusRequester = FocusRequester()
val keyboardController = LocalSoftwareKeyboardController.current

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

DisposableEffect(Unit) {
    focusRequester.requestFocus()
    onDispose { }
}
Related