constraintlayout icon indicating copy to clipboard operation
constraintlayout copied to clipboard

[Compose] Issue using Chains and Guidelines at the same time

Open eaduque opened this issue 2 years ago • 1 comments

I am trying to get a custom layout using this library but the behavior is not as expected. I have written the solution in two different ways (Code 1 and Code 2) but neither works correctly. When I apply the vertical chain the components are aligned to the edges of the parent.

Expected Result
Code 1
@Composable
fun MyScreen() {
    ConstraintLayout(
        ConstraintSet {
            val topGuideline = createGuidelineFromTop(0.1F)
            val bottomGuideline = createGuidelineFromBottom(0.1F)
            val txt1 = createRefFor("txt1")
            val txt2 = createRefFor("txt2")
            val txt3 = createRefFor("txt3")

            constrain(txt1) { linkTo(parent.start, topGuideline, parent.end, txt2.top) }
            constrain(txt2) { linkTo(parent.start, txt1.bottom, parent.end, txt3.top) }
            constrain(txt3) { linkTo(parent.start, txt2.bottom, parent.end, bottomGuideline) }

            createVerticalChain(txt1, txt2, txt3, chainStyle = ChainStyle.SpreadInside)
        },
        Modifier.fillMaxSize()
    ) {
        Text(text = "Text 1", modifier = Modifier.layoutId("txt1"))
        Text(text = "Text 2", modifier = Modifier.layoutId("txt2"))
        Text(text = "Text 3", modifier = Modifier.layoutId("txt3"))
    }
}
Code 2
@Composable
fun MyScreen() {
    ConstraintLayout(modifier = Modifier.fillMaxSize()) {
        val (txt1, txt2, txt3) = createRefs()
        val topGuideline = createGuidelineFromTop(0.1F)
        val bottomGuideline = createGuidelineFromBottom(0.1F)

        createVerticalChain(txt1, txt2, txt3, chainStyle = ChainStyle.SpreadInside)

        Text(text = "Text 1", Modifier.constrainAs(txt1) {
            linkTo(parent.start, topGuideline, parent.end, txt2.top)
        })
        Text(text = "Text 2", Modifier.constrainAs(txt2) {
            linkTo(parent.start, txt1.bottom, parent.end, txt3.top)
        })
        Text(text = "Text 3", Modifier.constrainAs(txt3) {
            linkTo(parent.start, txt2.bottom, parent.end, bottomGuideline)
        })
    }
}

Thanks for your help!! 😄💪🏻

eaduque avatar Sep 07 '22 02:09 eaduque

Try instead

val vChain = createVerticalChain(txt1, txt2, txt3, chainStyle = ChainStyle.SpreadInside)
constrain(vChain) {
   top.linkTo(topGuideline)
   bottom.linkTo(bottomGuideline)
}

The chain will otherwise ignore the constrains applied on the same axis.

oscar-ad avatar Sep 21 '22 22:09 oscar-ad