Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack-compose-text

How to chain two text with ConstraintLayout


I'm using ConstraintLayout for Compose and I'm facing a problem here.

I have a Text that is :

Text(
   text = "Whatever",
   overflow = TextOverflow.Ellipsis,
   maxLines = 1,
   modifier = Modifier
     .padding(start = 16.dp)
     .constraintAs(title) {
        start.linkTo(parent.start)
        bottom.linkTo(parent.bottom, 24.dp)
        end.linkTo(images.start)
        width = Dimension.fillToConstraints
     },
   )

That's a simple Text and then I have a Row where it's a dynamic number of Image for instance :

Row(
  modifier = Modifier
      .constraintAs(images) {
          start.linkTo(title.end)
          top.linkTo(title.top)
          bottom.linkTo(title.bottom)
          end.linkTo(parent.end, 16.dp)
       },
) {
  repeat(dynamicNumber) {
    Image(
       painter = painterResource...
       modifier = Modifier.padding(horizontal = 3.dp)
   )
  }
}

The problem I'm having here is with this code when the "Title" is long it fits perfect and is what I expect see the image below :

enter image description here

The problem is when the text is small the images are stick to the end because I've put end.linkTo(parent.end)

This is how it looks now : enter image description here

This is how should be : enter image description here

The idea is if the text is large, then its width is enough to don't overlap the images and when it's on its limit add the ellipse, then if the text is small the images should be not in the end but just stick to the small text.

What I'm missing?


Solution

  • Instead of using a ConstraintLayout, you can use a simple Row applying a weight(1f,false) modifier to the Text. Using fill=false the element will not occupy the whole width allocated.

       Row(Modifier.fillMaxWidth()) {
    
            Text(
                text = "Whatever",
                overflow = TextOverflow.Ellipsis,
                maxLines = 1,
                modifier = Modifier
                    .padding(start = 16.dp)
                    .weight(1f, false)
            )
    
           repeat(dynamicNumber) {
                Image(
                 painter = painterResource...
                 modifier = Modifier.padding(horizontal = 3.dp)
                )
           }
       }
    

    enter image description here