yao
yao

Reputation: 373

Why FocusManager doesn't work inside AlertDialog?

Does anyone knows how can I show or hide the keyboard inside AlertDialog?

The focusManager.clearFocus() doesn't work inside AlertDialog.

Same for textInputService?.hideSoftwareKeyboard() and softwareKeyboardController?.hide().

For example:

AlertDialog(
    onDismissRequest = {
        openDialog.value = false
    },
    text = {
        TextField(...)
    }
    buttons = {
        Button(
            modifier = Modifier.fillMaxWidth(),
            onClick = { focusManager.clearFocus() }
        ) {
            Text("Update")
        }
    }
)

Upvotes: 3

Views: 425

Answers (1)

Phil Dukhov
Phil Dukhov

Reputation: 87794

The AlertDialog, as any other Dialog, has its own LocalFocusManager as well as some other local constants.

You are capturing its value outside of AlertDialog, instead you need to capture it inside:

buttons = {
    val focusManager = LocalFocusManager.current
    Button(
        modifier = Modifier.fillMaxWidth(),
        onClick = { focusManager.clearFocus() }
    ) {
        Text("Update")
    }
}

Upvotes: 7

Related Questions