Search code examples
androidandroid-jetpack-composeandroid-alertdialogandroid-jetpack-compose-material3android-compose-dialog

Why can't I use Modifier.padding(top = 20.dp) to increase space in AlertDialog when I use JetPack Compose?


The Code A displays a dialog box based AlertDialog, and I get Image A when I run Code A.

I find the space between title = { Text(text = dialogTitle) } and text = {...} is too closer in Image A.

So I set Modifier.padding(top = 100.dp) to wish to increase the space between the two controls, but I only get Image B, it seems that Modifier.padding(top = 100.dp) doesn't work as expected, how can I fix it?

Code A

@Composable
fun EditTextDialog(
    isShow: Boolean,
    onDismiss: () -> Unit,
    onConfirm: (String) -> Unit,
    saveTitle: String = stringResource(R.string.dialog_save_title),
    cancelTitle:String = stringResource(R.string.dialog_cancel_title),
    dialogTitle:String ="Edit",  
    editFieldContent:String ="",
) {
    
    var mText by remember(editFieldContent){ mutableStateOf(editFieldContent) }
    
    val  cleanAndDismiss = {
        mText = editFieldContent 
        onDismiss()
    }

    if (isShow) {
        AlertDialog( 
            title = { Text(text = dialogTitle) },
            text = {
                Column(
                    Modifier.padding(top = 20.dp)
                    //Modifier.padding(top = 100.dp)
                     
                    //Modifier.height(100.dp),         //The same result as Image A
                    //verticalArrangement = Arrangement.Center
                ) {
                    TextField(
                        value = mText,
                        onValueChange = { mText = it }
                    )
                }
            },
              
             confirmButton = {
                TextButton(onClick = { onConfirm(mText) }) {
                    Text(text = saveTitle)
                }
            },

            dismissButton = {
                TextButton(onClick = cleanAndDismiss) {
                    Text(text = cancelTitle)
                }
            },

            onDismissRequest = cleanAndDismiss
        )
    }
}

Image A

enter image description here

Image B

enter image description here


Solution

  • With M3 AlertDialog (androidx.compose.material3.AlertDialog) it works.

    enter image description here

    With M2 AlertDialog, one solution is to remove the title attribute and use the text attribute for the whole layout.

      AlertDialog(
            onDismissRequest = {},
            text = {
                Column(){
                    Text(text = "Title")
                    Spacer(Modifier.height(30.dp))
                    TextField(
                        value = "mText",
                        onValueChange = { },
                    )
                }
            },
            //buttons..
        )