Position Alert dialog in Android Compose

Viewed 1677

How to position alert dialog in Jetpack Compose to the bottom of the screen. Also, set transparent background.

3 Answers

Thanks, @alekseyHunter & @johann. I can able to achieve this with custom layout modifier.

Custom modifier to position alert dialog

enum class CustomDialogPosition {
    BOTTOM, TOP
}

fun Modifier.customDialogModifier(pos: CustomDialogPosition) = layout { measurable, constraints ->

    val placeable = measurable.measure(constraints);
    layout(constraints.maxWidth, constraints.maxHeight){
        when(pos) {
            CustomDialogPosition.BOTTOM -> {
                placeable.place(0, constraints.maxHeight - placeable.height, 10f)
            }
            CustomDialogPosition.TOP -> {
                placeable.place(0,0,10f)
            }
        }
    }
}

And in alert dialog implementation as

AlertDialog( ..., modifiers = Modifiers.customDialogModifier(CustomDialogPosition.BOTTOM)) 
{
    // block
})

Look so simple.

Box(Modifier.fillMaxSize()) {
            Column() {
                /* Content */
            }
             /* Box alert */
            Box(
                Modifier
                    .padding(horizontal = 32.dp, vertical = 16.dp)
                    .fillMaxWidth()
                    .background(Color.Transparent, RoundedCornerShape(8.dp))
                    .border(2.dp, Color.LightGray, RoundedCornerShape(8.dp))
                    .align(Alignment.BottomCenter)
            ) {
                Text(
                    text = "Alert",
                    modifier = Modifier
                        .padding(16.dp)
                        .fillMaxWidth(),
                    textAlign = TextAlign.Center,
                    color = Color.Black
                )
            }
        }

The solution provided by @Rameshbabu changes the position of the dialog as expected. However, as was mentioned in the comments the dialog consequently becomes "fullscreen" and it can't be dismissed by tapping on the overlay.

I found another tricky solution. You can copy the source code of androidx.compose.ui.window.AndroidDialog.kt which comes with "androidx.compose.ui". By doing this you'll be able to access the dialog's window directly and change its gravity and other parameters.

The simplest way would be to add some code in the androidx.compose.ui.window.DialogWrapper class. For example in the init function:

private class DialogWrapper(
    private var onDismissRequest: () -> Unit,
    ...
) : Dialog(ContextThemeWrapper(...){

...

init {
    val window = window ?: error("Dialog has no window")
    window.requestFeature(Window.FEATURE_NO_TITLE)
    window.setBackgroundDrawableResource(android.R.color.transparent)
    window.setGravity(Gravity.TOP) // This to be added

Hopefully, the Jetpack Compose team will make the compose Dialog more customizable in the future.

Related