4

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?

1 Answer 1

1

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 { }
}
Sign up to request clarification or add additional context in comments.

3 Comments

It works !! Thank you, but i have one question, what does interactionsource do in this case ?
@Chun2Maru Check also developer.android.com/reference/kotlin/androidx/compose/… In this case is used to get info about the focused state.
@GabrieleMariotti I am going this route and I experience so many problems - i.e. - if component has requested focus then it tries to keep this focus indefinitely. E.g. when user clicks outside the component (TextField), the component still keeps focus and keeps the IME open and it is really disturbing behavior that should be hacked specifically. Maybe by releasing focusRequester. I think that it could be better just to put cursor inside TextField (or "click programmatically inside TextField") and let the Android concern about the focus flows itself, not to meddle with focus.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.