How to change the width of dialog in android compose

Viewed 2070

It seems impossible to change the width of the dialog with Compose. The closest I've come to with changing the dialog width is through DialogProperties.usePlatformDefaultWidth. Setting it to false causes the dialog to fill the screen but is there a way to use custom width?

2 Answers

Use can define a custom AlertDialog using the constructor with text,title and buttons parameters and applying a size (for example with the Modifier.size) and overriding the default behaviour with usePlatformDefaultWidth = false :

AlertDialog(
    onDismissRequest = { /*TODO*/ },
    title = {
        Text(text = "Title")
    },
    text = {
        Text(
            "This area typically contains the supportive text " +
                    "which presents the details regarding the Dialog's purpose."
        )
    },
    buttons = {},
    properties = DialogProperties(
        usePlatformDefaultWidth = false
    ),
    modifier = Modifier.size(200.dp,250.dp)
)

enter image description here

If you want to use a constant width in all your project you can create a dialog with customized width as follows

@Composable
fun MyCustomDialog(
    onDismissRequest: () -> Unit,
    properties: DialogProperties = DialogProperties(),
    content: @Composable () -> Unit
) {
    Dialog(
        onDismissRequest = onDismissRequest,
        // We are copying the passed properties 
        // then setting usePlatformDefaultWidth to false
        properties = properties.let {
            DialogProperties(
                dismissOnBackPress = it.dismissOnBackPress,
                dismissOnClickOutside = it.dismissOnClickOutside,
                securePolicy = it.securePolicy,
                usePlatformDefaultWidth = false
            )
        },
        content = {
            Surface(
                color = Color.Transparent,
                modifier = Modifier.width(250.dp), // Customize your width here
                content = content
            )
        }
    )
}
Related