I have a composable function with TextField
:
val focusManager = LocalFocusManager.current
TextField(
keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Search,
),
keyboardActions = KeyboardActions(
onSearch = {
focusManager.clearFocus()
}
)
)
and I need to show keyboard from inside of composable function as well as outside of it when I click on other button which is not part of composable content. Basically I wanna call hideKeyboard()
from my fragment.
I tried to use livedata inside composable:
val shouldShowKeyBoard by shouldShowSearchKeyBoard.observeAsState()
and I can do focusManager.clearFocus()
to hide keyboard but I'm not sure how to show it programmatically for specific compose TextField
What's the "compose" way to manage hide/show keyboard?
You can perform some action on state changes and you can do it using the side effects.
For example you can use the LaunchedEffect
function, where as a key
you can pass a state you want to listen.
LaunchedEffect(booleanValue) {
//...do something
}
You can use a ViewModel to set a boolean value and something like:
// initialize focus reference to be able to request focus programmatically
val focusRequester = remember { FocusRequester() }
LaunchedEffect(viewModel.showKeyboard) {
focusRequester.requestFocus()
}
TextField(
value = text,
onValueChange = {
text = it },
modifier = Modifier
// add focusRequester modifier
.focusRequester(focusRequester)
)
Just a note: to hide the keyboard you can also use:
val keyboardController = LocalSoftwareKeyboardController.current
TextField(
//...
keyboardActions = KeyboardActions(
onSearch = { keyboardController?.hide() }
)
Use the method focusManager.clearFocus()
to dismiss the keyboard and clear the focus.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With