Jetpack Compose: how to right align container that wraps content

1.1k Views Asked by At

I'd like to right-align a text bubble like so:

enter image description here

What do I need to do to get the desired result, and what exactly is going on as far as when each view in the sequence is being measured?

2

There are 2 best solutions below

0
On

You can use Spacer with weight to achieve this.

Row(modifier = Modifier.fillMaxWidth()){
    Spacer(modifier = Modifier.weight(1f))
    Text(modifier = Modifier
        .background(color = colorResource(id = R.color.light_gray), shape = RoundedCornerShape(8.dp))
        .padding(8.dp),text = "Yes")
}

First create a Row with max width. Now create a Spacer with weight 1f which occupy all the available space in your row. Now whatever you add after the spacer will be aligned at the end of your row.

0
On

The Row composable has a modifier property set to Modifier.fillMaxWidth() which makes it fill the width of its parent container. The horizontalArrangement property of the Row is set to Arrangement.End which aligns the child elements of the Row to the right end of the container.

Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
    Text(
         text = "Yes", modifier = Modifier
           .background(Color.LightGray, RoundedCornerShape(12.dp))
           .padding(10.dp)
     )
}