Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To automatically focus on a text field upon navigation to a composable in Jetpack Compose, you can use the onCommit parameter of the TextField composable.

Here's an example:

@Composable
fun MyScreen() {
    val focusRequester = remember { FocusRequester() }
    Column(
        Modifier
            .fillMaxSize()
            .focusRequester(focusRequester)
    ) {
        // Other composable elements
        TextField(
            value = /* your text state value */,
            onValueChange = /* your text state update logic */,
            modifier = Modifier
                .focusRequester(focusRequester)
                .onFocusEvent { focusState ->
                    if (focusState.hasFocus) {
                        // TODO: handle keyboard visibility if needed
                    }
                }
                .onCommit {
                    // Automatically request focus when the keyboard is opened
                    focusRequester.requestFocus()
                }
        )
    }
}

In this example, we first create a focusRequester using the remember function to ensure it retains its state across recompositions. We then apply this focus requester to both the parent Column and the TextField modifier.

The TextField composable also includes an onFocusEvent parameter, which we use here to detect when the field receives focus, and handle any necessary keyboard visibility adjustments. Finally, we use the onCommit parameter to automatically request focus when the keyboard is opened.