Skip to content
Velloreth
Android Development 8 min read

Jetpack Compose Layouts: ConstraintLayout and Beyond

A practical guide to Compose layouts — when ConstraintLayout is worth using, how its DSL works, and the layout patterns that replace nested Row and Column trees.

By

In the View system, ConstraintLayout existed largely for performance: a flat hierarchy of constrained Views beat nested LinearLayouts. That argument does not apply in Compose. The runtime handles deep layout trees efficiently, so nesting a Column inside a Row inside a Box is fine.

ConstraintLayout in Compose earns its place for a different reason: positioning. When elements need to relate to each other in ways that are not a simple vertical or horizontal stack — overlapping cards, a label pinned to an icon’s corner, a form that rearranges between phone and tablet — constraints express the intent more clearly than a pile of Box offsets.

This post covers when to use it, how the DSL actually works, and the helper concepts (guidelines, barriers, chains) that map to problems you already solved with nested layouts in XML.

The mental model

A ConstraintLayout holds children. Each child that you want to position gets a reference (a virtual ID). You then define constraints between references: “this top edge links to that bottom edge with a 16dp margin.” At composition time, the layout solves the constraint graph and places every child.

The dependency is androidx.constraintlayout:constraintlayout-compose. Check the release page for the current version; it is versioned separately from Compose itself.

There are two ways to write constraints:

StyleWhere constraints liveBest for
Inline (constrainAs)On each composable, in a modifierSimple, static layouts
Decoupled (ConstraintSet)In a separate ConstraintSet blockLayouts that change by state, size class, or orientation

Inline constraints with createRefs

The basic pattern: create references with createRefs(), then bind each composable with Modifier.constrainAs:

@Composable
fun LoginForm() {
    ConstraintLayout(Modifier.fillMaxSize().padding(16.dp)) {
        val (title, email, password, button) = createRefs()

        Text(
            text = "Sign in",
            style = MaterialTheme.typography.headlineMedium,
            modifier = Modifier.constrainAs(title) {
                top.linkTo(parent.top, margin = 32.dp)
                centerHorizontallyTo(parent)
            }
        )

        OutlinedTextField(
            value = email,
            onValueChange = { email = it },
            label = { Text("Email") },
            modifier = Modifier.constrainAs(email) {
                top.linkTo(title.bottom, margin = 24.dp)
                start.linkTo(parent.start)
                end.linkTo(parent.end)
            }
        )

        OutlinedTextField(
            value = password,
            onValueChange = { password = it },
            label = { Text("Password") },
            modifier = Modifier.constrainAs(password) {
                top.linkTo(email.bottom, margin = 12.dp)
                start.linkTo(email.start)
                end.linkTo(email.end)
            }
        )

        Button(
            onClick = { /* ... */ },
            modifier = Modifier.constrainAs(button) {
                top.linkTo(password.bottom, margin = 24.dp)
                centerHorizontallyTo(parent)
            }
        ) {
            Text("Continue")
        }
    }
}

A few things to notice. parent is a built-in reference to the ConstraintLayout itself. linkTo takes the anchor on the other reference, plus an optional margin. centerHorizontallyTo and centerVerticallyTo are sugar for linking both sides with bias 0.5. Vertical anchors are top, bottom, baseline; horizontal anchors are start, end (RTL-aware — prefer them over left/right).

Sizing: wrap, fixed, and match constraints

In the View system you had wrap_content, match_parent, and 0dp (match constraints). Compose has an equivalent model:

  • Omit a width/height modifier → the child measures itself (wrap).
  • Use Modifier.width(X.dp) or height → fixed.
  • Link both horizontal (or vertical) anchors without a size → the child fills the space between constraints, minus margins. This is the 0dp behavior.

One subtlety from the View system carries over: if you link both sides and set a fixed size, the child centers between the constraints according to a bias value (default 0.5). You can override bias in the linkTo call:

Text(
    text = "Badge",
    modifier = Modifier.constrainAs(badgeRef) {
        top.linkTo(parent.top)
        bottom.linkTo(parent.bottom)
        start.linkTo(parent.start, margin = 8.dp)
        end.linkTo(parent.end)
        bias = 0.2f // 20% from start, not centered
    }
)

You can also set aspect ratios when at least one dimension is match-constraints:

Image(
    painter = painterResource(R.drawable.hero),
    contentDescription = null,
    modifier = Modifier.constrainAs(imageRef) {
        top.linkTo(parent.top)
        start.linkTo(parent.start)
        end.linkTo(parent.end)
        ratio = "16:9"
    }
)

Guidelines

Guidelines are invisible lines you can constrain to — a fixed offset from an edge, or a percentage. They replace the “content column that starts 10% in from each side” pattern:

ConstraintLayout(Modifier.fillMaxSize()) {
    val startGuideline = createGuidelineFromStart(0.1f) // 10% from start
    val endGuideline = createGuidelineFromEnd(0.1f)
    val topGuideline = createGuidelineFromTop(24.dp)
    val (heading, body) = createRefs()

    Text(
        text = "Welcome",
        modifier = Modifier.constrainAs(heading) {
            top.linkTo(topGuideline)
            start.linkTo(startGuideline)
            end.linkTo(endGuideline)
        }
    )
    // body constrained similarly...
}

Percentage guidelines are the cleanest way to express “content column with responsive margins” without hardcoding dp values per breakpoint.

Barriers

A barrier is a virtual edge that tracks the extreme of several children. The classic use case: a label under two fields of different widths. You want the label to start below the taller of the two, not below the first one you happened to measure:

ConstraintLayout {
    val (name, email, label) = createRefs()
    val fieldsBarrier = createBottomBarrier(name, email)

    OutlinedTextField(
        value = name,
        onValueChange = { name = it },
        label = { Text("Name") },
        modifier = Modifier.constrainAs(name) {
            top.linkTo(parent.top)
            start.linkTo(parent.start)
        }
    )

    OutlinedTextField(
        value = email,
        onValueChange = { email = it },
        label = { Text("Email (optional)") },
        modifier = Modifier.constrainAs(email) {
            top.linkTo(parent.top)
            start.linkTo(name.end, margin = 8.dp)
            end.linkTo(parent.end)
        }
    )

    Text(
        text = "Required fields marked with *",
        modifier = Modifier.constrainAs(label) {
            top.linkTo(fieldsBarrier, margin = 8.dp)
            start.linkTo(parent.start)
        }
    )
}

createTopBarrier, createBottomBarrier, createStartBarrier, and createEndBarrier all work the same way: give them a set of references, and the barrier sits at the most extreme edge of that set. When any of those children resize (say, the email field wraps to two lines), the barrier moves and everything below it follows.

Chains

A chain links a group of children bidirectionally along one axis, then distributes the free space according to a style. This replaces evenly-spaced button rows and segmented controls:

ConstraintLayout {
    val (cancel, save, delete) = createRefs()

    createHorizontalChain(
        cancel, save, delete,
        chainStyle = ChainStyle.SpreadInside
    )

    Button(onClick = {}, modifier = Modifier.constrainAs(cancel) {
        top.linkTo(parent.top, margin = 16.dp)
    }) { Text("Cancel") }

    Button(onClick = {}, modifier = Modifier.constrainAs(save) {
        top.linkTo(parent.top, margin = 16.dp)
    }) { Text("Save") }

    Button(onClick = {}, modifier = Modifier.constrainAs(delete) {
        top.linkTo(parent.top, margin = 16.dp)
    }) { Text("Delete") }
}

The three chain styles:

StyleBehavior
SpreadEqual space between all items and at both ends
SpreadInsideEqual space between items; first and last flush to constraints
PackedAll items centered together, free space at both ends

Chains can be weighted: give one child Modifier.weight()-like behavior via ChainStyle.Packed plus bias, or spread weights explicitly. Vertical chains work identically with createVerticalChain.

The ConstraintSet pattern

When your layout needs to change — portrait versus landscape, compact versus expanded width, collapsed versus expanded card — define each layout as a ConstraintSet and pass the right one in:

@Composable
fun AdaptiveProfileCard() {
    BoxWithConstraints {
        val cs = if (maxWidth < 600.dp) compactConstraints() else expandedConstraints()

        ConstraintLayout(cs, Modifier.fillMaxSize().padding(16.dp)) {
            val avatar = createRefFor("avatar")
            val name = createRefFor("name")
            val bio = createRefFor("bio")

            Image(
                painter = painterResource(R.drawable.avatar),
                contentDescription = null,
                modifier = Modifier
                    .size(72.dp)
                    .clip(CircleShape)
                    .layoutId("avatar")
            )
            Text("Jitesh Prakash", modifier = Modifier.layoutId("name"))
            Text("Android developer", modifier = Modifier.layoutId("bio"))
        }
    }
}

private fun compactConstraints() = ConstraintSet {
    val avatar = createRefFor("avatar")
    val name = createRefFor("name")
    val bio = createRefFor("bio")
    constrain(avatar) {
        top.linkTo(parent.top)
        start.linkTo(parent.start)
    }
    constrain(name) {
        top.linkTo(avatar.bottom, margin = 8.dp)
        start.linkTo(parent.start)
        end.linkTo(parent.end)
    }
    constrain(bio) {
        top.linkTo(name.bottom, margin = 4.dp)
        start.linkTo(parent.start)
        end.linkTo(parent.end)
    }
}

private fun expandedConstraints() = ConstraintSet {
    val avatar = createRefFor("avatar")
    val name = createRefFor("name")
    val bio = createRefFor("bio")
    constrain(avatar) {
        top.linkTo(parent.top)
        start.linkTo(parent.start)
    }
    constrain(name) {
        top.linkTo(avatar.top)
        start.linkTo(avatar.end, margin = 16.dp)
    }
    constrain(bio) {
        top.linkTo(name.bottom, margin = 4.dp)
        start.linkTo(name.start)
    }
}

Two things to keep in mind. First, composables bind to the ConstraintSet with Modifier.layoutId("name") — the string IDs must match the createRefFor names. Second, remember the ConstraintSet if it is built from state, or build constant ones at the top level so they are not reallocated on recomposition. If the ConstraintSet block reads a State or other snapshot-backed value, wrap it in remember { derivedStateOf { ConstraintSet { ... } } }.

This pattern also gives you animations for free: pass animateChangesSpec = tween(300) and switching the ConstraintSet animates children between positions.

When to use what: a decision guide

Layout problemPrefer
Vertical stack of itemsColumn (+ weight for flexible children)
Horizontal row of itemsRow
Overlapping elements, or positioning relative to siblingsConstraintLayout
Content pinned to edges with a flexible centerBox with align modifiers
Same screen, different arrangements by widthConstraintSet + BoxWithConstraints or window size classes
Evenly distributed controls in a rowChain inside ConstraintLayout, or Row with Arrangement.SpaceEvenly
Complex animated transitions between statesMotionLayout (still built on ConstraintLayout)

The practical rule: start with the simplest structure that works. A Column with weights handles the majority of screens. Reach for ConstraintLayout when you find yourself writing negative offsets in a Box, or nesting three Rows to fake a grid. The constraint graph makes the intent explicit, and the ConstraintSet variant makes the adaptive behavior testable as data rather than as scattered modifier conditionals.

Where ConstraintLayout is still not the answer

Two common mistakes worth calling out.

Using it for simple stacks. A ConstraintLayout with five constrainAs blocks to stack five items is strictly worse than a Column. The constraint DSL adds ceremony without adding meaning. Future-you reading a Column knows exactly what happens; reading a constraint graph for a linear stack requires more work.

Mixing inline and ConstraintSet styles inconsistently. If a screen has one ConstraintLayout with inline constraints and another with a ConstraintSet, pick one style per screen. Inline for a purely static form is fine. The moment that screen needs a landscape variant, migrate the whole screen to ConstraintSet rather than bolting conditionals onto constrainAs blocks.

ConstraintLayout is a sharp tool for positioning problems. Used where it fits, it replaces fragile offset math with a declarative graph. Used everywhere, it turns readable UI code into a constraint-solving exercise. Start with Column and Box, and promote to constraints when the layout stops being linear.

Frequently asked questions

When should I use ConstraintLayout in Compose?
Use it when elements are positioned relative to each other in non-linear ways — overlapping views, bias-based positioning, or layouts that change between orientations. For simple linear stacks, Column and Row are clearer.
Is ConstraintLayout slower than Row and Column in Compose?
No. Compose handles deep hierarchies efficiently, so the old View-system argument for a flat hierarchy does not apply. Choose based on readability, not micro-performance.
What is the difference between constrainAs and ConstraintSet?
constrainAs defines constraints inline on each composable. A ConstraintSet defines all constraints in one place, and composables bind to it with layoutId. ConstraintSet is better when you swap layouts for different states or want animated transitions.
Can I animate between two ConstraintSets?
Yes. Pass animateChangesSpec to ConstraintLayout and switch the ConstraintSet; children animate to their new positions. For more control over intermediate states, use MotionLayout.