user3459435
user3459435

Reputation: 231

How to center text inside DropdownMenuItem in compose

Currently, when I create a DropdownMenu it always shows the text to the start. I want it to be centered and didn't find any resource that answers that.

Upvotes: 2

Views: 847

Answers (2)

Phil Dukhov
Phil Dukhov

Reputation: 87864

By default, Box wraps content size, so for a single view inside, without additional modifiers, contentAlignment makes no difference. For @Francesc's answer to work, you need to apply Modifier.fillMaxWidth() to the box:

DropdownMenuItem(onClick = {}) {
    Box(
        contentAlignment = Alignment.Center, 
        modifier = Modifier.fillMaxWidth()
    ) {
        Text(text = "text")
    }
}

Alternatively, you can do this without Box using textAlign parameter and you also need Modifier.fillMaxWidth():

DropdownMenuItem(onClick = {}) {
    Text(
        text = "text",
        textAlign = TextAlign.Center,
        modifier = Modifier.fillMaxWidth()
    )
}

Upvotes: 2

Francesc
Francesc

Reputation: 29270

The drop down item takes a composable, you can use a Box and set the content alignment to center

    DropdownMenu(
        expanded = expanded,
        onDismissRequest = { expanded = false },
        modifier = Modifier.fillMaxWidth())
    ) {
        items.forEachIndexed { index, s ->
            DropdownMenuItem(onClick = {
                selectedIndex = index
                expanded = false
            }) {
                val disabledText = if (s == disabledValue) {
                    " (Disabled)"
                } else {
                    ""
                }
                Box(contentAlignment = Alignment.Center) {
                    Text(text = s + disabledText)
                }
            }
        }
    }

Upvotes: 1

Related Questions