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

25.1k views Asked by At

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

5

There are 5 answers

3
Gabriele Mariotti On BEST ANSWER

You have to use a parent container and align the composable inside it.

For example a Box:

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

or a Column:

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

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!")
    }
}
0
Thracian On

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.

0
evaristokbza On

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")
}
0
The MJ On

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