Stylianos Gakis
02/01/2022, 4:23 PMStylianos Gakis
02/01/2022, 4:23 PM@Composable
fun Comp() {
val focusRequester = remember { FocusRequester() }
DisposableEffect(Unit) {
focusRequester.requestFocus()
onDispose {
focusRequester.freeFocus() // Might not even need this since at this point I've left this screen
}
}
BasicTextField(modifier = Modifier.focusRequester(focusRequester))
}
But I am getting the error of:
1. Remember the FocusRequester: val focusRequester = remember { FocusRequester() }
2. Did you forget to add a Modifier.focusRequester() ?
3. Are you attempting to request focus during composition? Focus requests should be made in
response to some event. Eg Modifier.clickable { focusRequester.requestFocus() }
I canât find anything in the documentation regarding focus aside from just the package reference but it doesnât help with my use case.
What is the proper way to achieve this?Stylianos Gakis
02/01/2022, 4:30 PMLaunchedEffect
instead of `DisposableEffect`:
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
Seems to be getting the focus alright. I guess LaunchedEffect happens 1 frame after composition suceeded, while DisposableEffect happens at composition and the focusRequester modifier wasnât called yet. And it even opened the keyboard once, but itâs not consistent about it đ€
Plus I am getting a super weird case where I use the âbackâ gesture and the keyboard opens and closes instead of going back, but at this point Iâm pretty sure I must be messing something up badly. Is there any sort of official documentation about handling focus that I can follow to avoid all these weird things I am doing đJoseph Hawkes-Cates
02/01/2022, 4:33 PMJoseph Hawkes-Cates
02/01/2022, 4:35 PMFunkyMuse
02/01/2022, 7:36 PM@Composable
fun SearchBarComponent(
keyboardController: SoftwareKeyboardController? = LocalSoftwareKeyboardController.current,
onTextChanged: ((String) -> Unit)? = null,
) {
var text by rememberSaveable { mutableStateOf("") }
val focusRequester = remember { FocusRequester() }
TextField(
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester)
.height(56.dp),
value = text,
onValueChange = {
text = it
onTextChanged?.invoke(it)
})
DisposableEffect(Unit) {
focusRequester.requestFocus()
keyboardController?.show()
onDispose {
focusRequester.freeFocus()
keyboardController?.hide()
}
}
}
Stylianos Gakis
02/02/2022, 9:08 AMFunkyMuse
02/02/2022, 11:52 AM