3

I have a TextField and a ModalDrawer in a compose screen. I would like to close the soft keyboard when the user opens the drawer, but I haven't been able to figure out how. There is no onOpened lifecycle event that gets triggered in ModalDrawer afaik.

kc_dev
  • 578
  • 1
  • 6
  • 21

1 Answers1

4

You can use the confirmStateChange parameter in rememberDrawerState() and call keyboardController.hide() when the drawerValue becomes DrawerValue.open like this:

val keyboardController = LocalSoftwareKeyboardController.current
val state = rememberDrawerState(
  initialValue = DrawerValue.Closed,
    confirmStateChange = {
       if (it == DrawerValue.Open) {
           keyboardController?.hide()
       }
       true
    }
)

ModalDrawer(
   drawerState = state,
   ...
) {
  ...
}
Aburg
  • 246
  • 1
  • 6
  • 2
    This is what I was looking for! I do have one caveat though; for anyone reading this answer, `confirmStateChange` lambda expects a `boolean`, so you will need to add `true` at the end of it. – kc_dev Dec 22 '21 at 00:37
  • This is correct! I will update my answer. – Aburg Dec 22 '21 at 15:59
  • The only problem I see is `confirmStateChange` doesn't get called when you call `show()` or `hide()` on the drawer. It only gets called when the user slides the drawer in or out (or taps on the scrim which dismisses the keyboard). If you call `show()` when a button is pushed, then this won't help. – Kevin Worth May 22 '23 at 21:53
  • ...so, for button press, duplicate the logic and put it in the button's `onClick` as well. – Kevin Worth May 22 '23 at 22:10