9

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

danartillaga
  • 696
  • 5
  • 14

5 Answers5

16

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",
    )
}
Gabriele Mariotti
  • 250,295
  • 77
  • 670
  • 690
3

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")
}
evaristokbza
  • 763
  • 2
  • 13
  • 24
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.

Thracian
  • 13,723
  • 7
  • 65
  • 116
1

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

The MJ
  • 263
  • 3
  • 15
0

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!")
    }
}
Vikas Patidar
  • 41,973
  • 22
  • 91
  • 104