How to add divider in title in Alert Dialog in jetpack compose

628 Views Asked by At

I want to add Divider after title. I tried to add Divider(), but it goes to above the text.

I am using Material 3 using implementation "androidx.compose.material3:material3:1.0.1"

import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Divider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.letsgetchecked.app.common.DialogOptionsData

@Composable
fun <T> DialogOptionsView(
    optionData: DialogOptionsData<T>,
) {
    AlertDialog(
        onDismissRequest = {},
        confirmButton = {},
        title = {
            Text(text = optionData.header)
            Divider()
        },
        text = {
            LazyColumn {
                items(optionData.items) {
                    Text(text = "$it")
                }
            }
        },
    )
}

@Preview(showBackground = true)
@Composable
fun PreviewDialogOptions() {
    val items = listOf(1, 2)
    val dataItems = DialogOptionsData(header = "Header", items = items)
    DialogOptionsView(dataItems)
}

Expected Output

enter image description here

Actual Output

enter image description here

2

There are 2 best solutions below

2
Gabriele Mariotti On BEST ANSWER

It happens because the title attribute internally uses a Box as parent container.
Add a Column to achieve the expected result:

    AlertDialog(
        onDismissRequest = {},
        confirmButton = {},
        title = {
            Column() {
                Text(text = "header")
                Divider()
            }
        },

enter image description here

0
Sri mani789 On

If you use Dialog() composable instead of AlertDialog() you can get full width divider. Try this code

@Composable
fun <T> DialogOptionsView(optionData: DialogOptionsData<T>) {
    Dialog(onDismissRequest = {}) {
        Surface(shape = RoundedCornerShape(10.dp)) {
            Column {
                Text(
                    text = optionData.header,
                    style = MaterialTheme.typography.titleMedium,
                    modifier = Modifier.padding(16.dp, 14.dp)
                )
                Divider()
                LazyColumn(contentPadding = PaddingValues(16.dp, 10.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    items(optionData.items) {
                        Text(text = "$it")
                    }
                }
            }
        }
    }
}

and the result is

full width diider