Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Insert composable from another fun into main ConstraintLayout

I want to create one custom composable in a fun, and then add that composable into another fun that contains my main ConstraintLayout with all the composables for the layout.
I am having trouble with the constraints when I try to do this, I get the composable into the ConstraintLayout, but it is stuck in the top left/start corner.

How can I correctly add constraints to this composable that is built and comes from another fun into my main ConstraintLayout fun?

My code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@Composable
fun MainConstraintLayout() {
    ConstraintLayout {
        val (view1, view2) = createRefs()

        Button(onClick = { /*....*/ },
            modifier = Modifier.constrainAs(view1) {
                top.linkTo(parent.top)
                start.linkTo(parent.start)
                end.linkTo(parent.end)
            }
        ) { Text("view1, correct constraints") }

        // How can I constraint this view (below) to the bottom of view1?
        MyOneComposable()
    }
}

@Composable
fun MyOneComposable() {
    Button(onClick = { /*....*/ }) {
        Text(text = "My one composable button")
    }
}

>Solution :

You need to pass Modifier parameter into your MyOneComposable:

@Composable
fun MyOneComposable(
    modifier: Modifier,
) {
    Button(onClick = { /*....*/ }, modifier = modifier) {
        Text(text = "My one composable button")
    }
}

So you can apply ref modifier from ConstraintLayout:

MyOneComposable(Modifier.constraintAs(view2) { ... })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading