Home > Mobile >  How to add divider in title in Alert Dialog in jetpack compose
How to add divider in title in Alert Dialog in jetpack compose

Time:02-03

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

CodePudding user response:

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

  • Related