androidandroid-jetpack-composeandroid-alertdialogandroid-jetpackandroid-compose-dialog

Show custom alert dialog in Jetpack Compose


I am searching how create custom dialog in Jetpack Compose. In XML or Material Design we can create easily custom Dialog in which we can take user input, radio button etc. but i am not finding such thing in Jetpack Compose.


Solution

  • Starting from M3 1.1.0-alpha04 there is an AlertDialog composable function with a slot for content.

    val openDialog = remember { mutableStateOf(true) }
    
    if (openDialog.value) {
        androidx.compose.material3.AlertDialog(
            onDismissRequest = {
                // Dismiss the dialog when the user clicks outside the dialog or on the back
                // button. If you want to disable that functionality, simply use an empty
                // onDismissRequest.
                openDialog.value = false
            }
        ) {
            Surface(
                modifier = Modifier
                    .wrapContentWidth()
                    .wrapContentHeight(),
                shape = MaterialTheme.shapes.large
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
    
                    //... AlertDialog content
                }
            }
        }
    }
    

    enter image description here


    Before M3 1.1.0-alpha04 or with M2, you can use the standard AlertDialog.
    The text,title and buttons parameters support @Composable functions and in this way you can customize the dialog as you prefer.

    For example:

    val openDialog = remember { mutableStateOf(true) }
    var text by remember { mutableStateOf("") }
    
    if (openDialog.value) {
        AlertDialog(
            onDismissRequest = {
                openDialog.value = false
            },
            title = {
                Text(text = "Title")
            },
            text = {
                Column() {
                    TextField(
                        value = text,
                        onValueChange = { text = it }
                    )
                    Text("Custom Text")
                    Checkbox(checked = false, onCheckedChange = {})
                }
            },
            buttons = {
                Row(
                    modifier = Modifier.padding(all = 8.dp),
                    horizontalArrangement = Arrangement.Center
                ) {
                    Button(
                        modifier = Modifier.fillMaxWidth(),
                        onClick = { openDialog.value = false }
                    ) {
                        Text("Dismiss")
                    }
                }
            }
        )
    }
    

    enter image description here