Chun2Maru
Chun2Maru

Reputation: 43

Programmatically click textfield in jetpack compose

Is there a way to click textfield programmatically so when my search screen pops up, it automaticaly clicks the textfield and also pop up the keyboard. Or maybe, is there a way to know the touch event of the textfield?

Upvotes: 4

Views: 3723

Answers (1)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363567

With 1.0.x you can give the focus to the component.
Something like:

var text by remember { mutableStateOf(TextFieldValue("text")) }
val focusRequester = FocusRequester()
val keyboardController = LocalSoftwareKeyboardController.current

val interactionSource = remember { MutableInteractionSource() }
val isFocused by interactionSource.collectIsFocusedAsState()

Column {
    TextField(
        value = text,
        onValueChange = {
            text = it
        },
        interactionSource = interactionSource,
        label = { Text("label") },
        modifier = Modifier
            // add focusRequester modifier
            .focusRequester(focusRequester)
            .onFocusChanged {
                if (isFocused) {
                    keyboardController?.show()
                }
            }
    )
}

and then:

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

Upvotes: 1

Related Questions