Search code examples
androidkotlinandroid-jetpack-composeimeandroid-jetpack-compose-ui

Android Compose: Is there any way to dismiss dialog on click of “Done” key from keyboard


I'm new to Android compose. Is there any way to dismiss dialog on click of Done key from keyboard using ImeAction?

Currently below code is clearfocus on click of Done along with how to dismiss the dialog:

    TextField(
        value = text,
        onValueChange = {
            text = it
        },
        singleLine = true,
        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
        keyboardActions = KeyboardActions(
            onDone = { focusRequester.requestFocus() }
        ),
        modifier = Modifier.onKeyEvent {
            if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_ENTER){
                focusRequester.requestFocus()
                true
            }
            false
        }
    )

Solution

  • Inside onDone set the flag you use to show dialog to false

    var showDialog by remember {mutableStateOf(false)}
    
     onDone = { 
        focusRequester.requestFocus()
        showDialog = false
     }
    
    if(showDialog) {
       AlerDialog(...)
    }
    

    You check out the link below to show dialogs

    Show custom alert dialog in Jetpack Compose