2
Text(
    modifier = Modifier
        .fillMaxWidth()
        .background(Color.Black),
    minLines = 3,
    textAlign = TextAlign.Center,
    text = "Not centered vertically"
)

enter image description here

How can I center text by vertically and horizontally of its container when current lines count is less then minimum lines?

user924
  • 8,146
  • 7
  • 57
  • 139

2 Answers2

1

The textAlign attributes defines only how to align text horizontally.

You can use the TextMeasurer to measure a text and check if the width > width of the text. In this case the text will occupy more than 1 line in the Text composable

In this example I am using the screen width (since you are using fillMaxWidth()).

    val textMeasurer = rememberTextMeasurer()
    val textLayoutResult: TextLayoutResult =
        textMeasurer.measure(
            text = AnnotatedString(text),
            style = LocalTextStyle.current
        )
    val widthText = textLayoutResult.size.width

    val density = LocalDensity.current
    val configuration = LocalConfiguration.current
    val screenWidth = density.run { configuration.screenWidthDp.dp.toPx()}

    Text(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.Black),
        minLines = 3,
        textAlign = TextAlign.Center,
        text = if (widthText < screenWidth)  "\n" + text else text,
        color = White,
    )

enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
0

textAlign is only responsible for horizontal alignment, usually to control vertical alignment you can use a container.

I like to use a technique where you add an invisible view that gives the layout some size guides, and then place the actual view using the parent alignment.

In this case, the blank text with minLines will take the necessary height, and the actual text will be centered in the box.

Box(
    contentAlignment = Alignment.Center,
    modifier = Modifier
        .fillMaxWidth()
        .background(Color.Black)
) {
    Text("", minLines = 3)
    Text(
        "Centered vertically",
        textAlign = TextAlign.Center,
        color = Color.White,
    )
}

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220