2

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?

Rainmaker
  • 8,993
  • 5
  • 45
  • 72

2 Answers2

6

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:

val focusRequester = 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.

Gabriele Mariotti
  • 250,295
  • 77
  • 670
  • 690
0

to add on Gabriele's answer, you will need val focusRequester = remember { FocusRequester() } or you will get an exception

peresisUser
  • 1,622
  • 16
  • 21