Stylianos 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?LaunchedEffect
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 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