'How to align Text to Top, Bottom and Center Vertically in Jetpack Compose?

How can I align the text using Text composable function vertically. Is there a way to do it without having to add another extra view to contain the Text.

The textAlign parameter of Text only has the following options:

TextAlign.

  • Left
  • Right
  • Center
  • Justify
  • Start
  • End

I have tried using textAlign = TextAlign.Center but it only centers it horizontally. How can I center it vertically without wrapping it in another view?

Text(
    text = "Text",
    modifier = Modifier.size(100.dp),
    textAlign = TextAlign.Center
)

Result:

result

What I am trying to achieve:

what I am trying to achieve



Solution 1:[1]

You have to use a parent container.

For example:

Box( 
    modifier = Modifier.fillMaxSize(),
    contentAlignment = Center
) {
    Text(
        text = "Text",
    )
}

or:

Column(
    modifier = Modifier.fillMaxSize(),
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally
) {
    Text(
        text = "Text",
    )
}

Solution 2:[2]

It is difficult to give an exact answer without seeing your code, but I would say you need to use container's Alignment.CenterVertically instead of TextAlign

Something like:

Row {
    Text(
        text = "Text",
        modifier = Modifier.align(alignment = Alignment.CenterVertically)
    )

    Image(
        ...
    )
}

or:

Column(
    modifier = Modifier
        .align(Alignment.CenterVertically)
) {
    Text(text = "Text")
    Text(text = "Text 2")
}

Solution 3:[3]

I asked the same question here which is done with android:gravity param using views, as answered by PhilipDukhov it's not possible only with Text, you need to have another container, preferably Box to align Text component inside.

Solution 4:[4]

first use .wrapContentHeight() in modifier, then you can use align(CenterVertically) param to center the text.

Solution 5:[5]

Create a simple composable function to show anything in center:

@Composable
fun Center(
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit,
) {
    Box(
        modifier = modifier,
        contentAlignment = Alignment.Center
    ) {
        content()
    }
}

Call it from any other function:

@Composable
fun CenterAlignedText() {
    Center(Modifier.fillMaxSize()) {
        Text("Hello World!")
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabriele Mariotti
Solution 2
Solution 3
Solution 4 The MJ
Solution 5 Vikas Patidar