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?
Asked
Active
Viewed 2,819 times
1 Answers
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 { }
}

Gabriele Mariotti
- 320,139
- 94
- 887
- 841
-
It works !! Thank you, but i have one question, what does interactionsource do in this case ? – Chun2Maru Apr 02 '21 at 10:41
-
@Chun2Maru Check also https://developer.android.com/reference/kotlin/androidx/compose/foundation/interaction/InteractionSource In this case is used to get info about the focused state. – Gabriele Mariotti Apr 02 '21 at 10:42
-
@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. – TomR Aug 19 '22 at 06:41