There are two scenarios
Scenario 1 - A TextField in an AlertDialog
Make sure to initialize the keyboard controller
or focus manager
inside the Dialog content scope
(Dialog has its own keyboard controller)
Dialog(
onDismissRequest = {
// on dismiss
}
) {
// initialise the keyboard controller and focus Manager inside the content scope
val keyboardController = LocalSoftwareKeyboardController.current
val focusManager = LocalFocusManager.current
}
hide the keyboard
keyboardController?.hide()
focusManager.clear()
Edge case - Dismiss the dialog and hide the keyboard
There might be a keyboard flickering (keyboard hide and show quickly) issue when dismissing the dialog and keyboard at the same time.
Try to hide the keyboard first then trigger the dismiss dialog event with a delay
Dialog() {
val keyboardController = LocalSoftwareKeyboardController.current
val focusManager = LocalFocusManager.current
Button(onClick = {
keyboardController?.hide()
focusManager.clear()
// notify the view model to dismiss the dialog
viewModel.onNegativeButtonClicked()
})
}
Inside the ViewModel
ViewModel {
fun onNegativeButtonClicked() {
// trigger dismissDialog event with delay
}
}
Scenario 2 - TextField only (no dialog)
val keyboardController = LocalSoftwareKeyboardController.current
var text by rememberSaveable { mutableStateOf("") }
TextField(
value = text,
onValueChange = { text = it },
label = { Text("Label") },
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(
onDone = {
keyboardController?.hide()
// do something here
}
)
)
or you can just use keyboardController
focusManager
to hide the keyboard inside the click event
Button(onClick = {
keyboardController?.hide()
})
AlertDialog
. Nothing I have tried,SoftwareKeyboardController
,FocusManager
, norFocusRequester
work in a dialog. Any ideas? – Shrieve