Search code examples
androidandroid-jetpack-composeandroid-jetpack-compose-layout

Android Compose horizontal alignment problem


I have a Android Compose layout issue. This example is simplified. So please don't worry about the hierarchy.

A card should contain two main content areas. One should take all available space starting from the left side. The other one is located at the right side and has a fixed width. I use a Spacer to keep it at the right side of the card.

It works fine if the text is short enough. If the text gets longer, it pushes the second one "from the card".

What should be changed that the first column takes only the available space?

Card(
            modifier = Modifier
                .fillMaxWidth()
                .height(150.dp)
                .padding(bottom = 16.dp),
            elevation = 0.dp,
            shape = RoundedCornerShape(11.dp)
        ) {
            Row {
                Column(
                    Modifier
                        .padding(top = 11.dp, bottom = 13.dp, end = 12.dp, start = 16.dp),
                ) {
                    Text(
                        text = "First Text gets very long. Two long for Text the second text. It gets pushed out of the screen.",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis
                    )
                }
                Spacer(Modifier.weight(1f))
                Column(
                    modifier = Modifier
                        .width(86.dp)
                        .fillMaxHeight()
                ) {
                    Text(
                        text = "Second Text",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Bold,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            }
        }

enter image description here

enter image description here


Solution

  • You can apply the weight modifier to the first Column removing the Spacer:

        Row(Modifier.height(IntrinsicSize.Min)) {
            Column(
                modifier = Modifier.weight(1f),
            ) {
                Text(
                    text = "First ......screen.",
                    //
                    overflow = TextOverflow.Ellipsis
                )
            }
            Column(
                modifier = Modifier
                    .width(86.dp)
                    .fillMaxHeight()
            ) {
                Text(
                    text = "Second Text",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
    

    enter image description here