Search code examples
androidkotlinandroid-jetpack-compose

How to Align Text to the End in a Column Layout in Jetpack Compose?


I'm working with Jetpack Compose and I’m trying to align a Text composable to the end of its parent layout. Here's the code I’m using:

@Composable
fun GreetingText(message: String, from: String, modifier: Modifier = Modifier) {
    Column(
        verticalArrangement = Arrangement.Center,
        modifier = modifier
    ) {
        Text(
            text = message,
            fontSize = 100.sp,
            lineHeight = 116.sp,
            textAlign = TextAlign.Center
        )
        Text(
            text = from,
            fontSize = 36.sp,
            modifier = Modifier
                .padding(16.dp)
                .align(alignment = Alignment.End) //  <- Alignment working as expected not sure why?
        )
    }
}

I expected that using 'textAlign = TextAlign.Center' on the second Text composable would align it to the end of the Text Component. However, it seems not to align it as expected.

Thanks in advance for any help


Solution

  • Use this:

    Text(
        text = message,
        fontSize = 100.sp,
        lineHeight = 116.sp,
        modifier = Modifier
            .align(Alignment.CenterHorizontally),
    )
    Text(
        text = from,
        fontSize = 36.sp,
        modifier = Modifier
            .padding(16.dp)
            .align(Alignment.End),
    )
    

    Please note the following:

    1. textAlign only aligns the text inside the Text composable (like a paragraph in a multiline Text). It does not align the Text composable in its parent layout, that's what the align modifier is for.

    2. The align modifier only alignes inside the Column, not inside the screen. When the Column doesn't fill out the entire screen width, the Text is only aligned in respect to the actual Column width.

      In your case the Column's width is the maximum width of its children. If both Text composables only display short texts the center and end alignment will only align in respect to the longest text:


      (Use the Layout Inspector in Android Studio to create this kind of view)

      If this is undesirable explicitly set the Column's width, for example to fillMaxWidth().

    3. The alignment of the second Text takes the padding into account. Although it is aligned with Alignment.End, There will always be an additional space of 16.dp at the end. If you don't want that, remove the padding.