Center Text in a TextView with width and height in Compose

Issue

I have this composable :

@Composable
fun MyApp() {

    var isSelected by remember { mutableStateOf(false) }
    val backgroundColor by animateColorAsState(if (isSelected) Color.Red else Color.Transparent)

    Column(
        modifier  Modifier
            .fillMaxSize(),
        verticalArrangement  Arrangement.Center,
        horizontalAlignment  Alignment.CenterHorizontally
    ) {
        Text(
            text  "Hello",
            modifier  Modifier.background(color  backgroundColor)
                .clickable(onClick  { isSelected  !isSelected })
                .width(100.dp)
                .height(40.dp),
            textAlign  TextAlign.Center,

        )
    }
}

I expect TextAlign.Center centerlize Text of TextView, but it will be just centerlize horizontally. How can I make it center vertically as well?

Solution

TextAlign.Center can only center your content horizontally.

To center it vertically you need to place it inside a container, like Box, and apply content alignment and your size modifiers to this container:

Column(
    modifier  Modifier
        .fillMaxSize(),
    verticalArrangement  Arrangement.Center,
    horizontalAlignment  Alignment.CenterHorizontally
) {
    Box(
        contentAlignment  Alignment.Center,
        modifier  Modifier
            .width(100.dp)
            .height(40.dp)
            .background(color  backgroundColor)
            .clickable(onClick  { isSelected  !isSelected })
    ) {
        Text(
            text  "Hello",
            textAlign  TextAlign.Center
        )
    }
}

Also I’d say that generally this is a bad practice, because when user increase text size in the phone accessibility settings, your Text may no longer fit your box. Consider using padding instead.

Answered By – Philip Dukhov

Leave a Comment