androidandroid-jetpack-composeandroid-constraintlayout

Compose ConstraintLayout does not respect constraints


I'm trying to use constraint layouts to lay down my elements, but they do not truly respect the constraint I gave to them when the content of this elements is bigger than the space available.

Is this I real limitation or I'm just using this layout for a wrong purpose?

Two elements in a constraint layout

I've try different version of it, but mostly they look like this:

@Composable
fun ConstrainedElements() {
    ConstraintLayout(modifier = Modifier.padding(WindowInsets.safeDrawing.asPaddingValues())) {

        val (button, title) = createRefs()

        RegularButton(text = "Play", modifier = Modifier.constrainAs(button) {
            top.linkTo(parent.top)
            bottom.linkTo(parent.bottom)
            start.linkTo(parent.start)
        })

        Title(
            title = "Title too long that should be wrapped always",
            modifier = Modifier.constrainAs(title) {
                top.linkTo(parent.top)
                bottom.linkTo(parent.bottom)
                start.linkTo(button.end)
                end.linkTo(parent.end)
            })
    }
}

@Composable
fun RegularButton(modifier: Modifier = Modifier, text: String) {
    Button(modifier = modifier, onClick = { /*TODO*/ }) {
        Text(text = text)
    }
}

@Composable
fun Title(modifier: Modifier = Modifier, title: String) {
    Text(
        text = title,
        fontSize = 18.sp,
        fontWeight = FontWeight.Bold,
        textAlign = TextAlign.Justify,
        overflow = TextOverflow.Ellipsis,
        modifier = modifier
    )
}

Solution

  • You need to explicitly specify the width that the Title Composable should take. In your case, you need to specify Dimension.fillToConstraints so that the Composable spreads to match the left and right Constraints:

    .constrainAs(title) {
        top.linkTo(parent.top)
        bottom.linkTo(parent.bottom)
        start.linkTo(button.end)
        end.linkTo(parent.end)
        width = Dimension.fillToConstraints  // add this line
    }
    

    If you don't specify any width in the constrainAs Modifier, the Text Composable will have wrapContentWidth by default, which can overflow the constraints given by the ConstraintLayout.

    Output:

    enter image description here