In Jetpack Compose, how do you write a custom Layout with its MeasurePolicy, and what stops it from measuring a child twice?
answer
- measure, decide size, place
- one measurement per child per pass
- ask intrinsics before measuring
- SubcomposeLayout pays for flexibility
basics
~20 sCall Layout with a MeasurePolicy that measures each child once, reports its size with layout(width, height) and places the Placeables. Compose throws if a child is measured twice; intrinsic measurements let a parent query sizes first.
solid answer
~30 sA custom layout is the `Layout` composable with a `MeasurePolicy`: the lambda gets the children's `measurables` and the parent's `constraints`, calls `measure()` once per child to get `Placeable`s, then returns `layout(width, height) { placeable.placeRelative(x, y) }`. Compose forbids multi-pass measurement: a second `measure()` on the same `Measurable` throws an `IllegalStateException`, which keeps deep nesting cheap. When a parent needs a size before choosing constraints, it uses intrinsics, such as `Modifier.height(IntrinsicSize.Min)`, and a custom `MeasurePolicy` can override `minIntrinsicHeight` and the rest because the defaults are approximations. `SubcomposeLayout`-based layouts like `BoxWithConstraints` defer composition into layout and do not support intrinsic queries.
code
kotlin · 24 linesimport androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.unit.constrainHeight
import androidx.compose.ui.unit.constrainWidth
@Composable
fun AvatarWithBadge(
modifier: Modifier = Modifier,
content: @Composable () -> Unit, // exactly two children: avatar, then badge
) {
Layout(content = content, modifier = modifier) { measurables, constraints ->
require(measurables.size == 2) { "AvatarWithBadge expects an avatar and a badge" }
val loose = constraints.copy(minWidth = 0, minHeight = 0)
val avatar = measurables[0].measure(loose)
val badge = measurables[1].measure(loose)
val width = constraints.constrainWidth(avatar.width + badge.width / 2)
val height = constraints.constrainHeight(avatar.height + badge.height / 2)
layout(width, height) {
avatar.placeRelative(x = 0, y = badge.height / 2)
badge.placeRelative(x = avatar.width - badge.width / 2, y = 0)
}
}
}go deeper
Recall the three steps of any Compose layout, measure children, choose a size, place children, and that Row and Column are built on the Layout composable.
Explain Constraints, Measurable and Placeable, why loose constraints matter, and what IntrinsicSize.Min does to a Row with a fillMaxHeight divider.
Write a correct MeasurePolicy under pressure, override intrinsics when parents query them, and explain when BoxWithConstraints or SubcomposeLayout is worth its cost and when a Layout is enough.
Weigh a shared custom layout against composing stock ones: who maintains its measure and intrinsic logic, and whether a design need justifies leaving Row, Column and Box.
## The contract: measure, size, place Every layout node in Jetpack Compose goes through the same three steps: **measure its children**, **decide its own size**, **place its children**. A parent passes each child a `Constraints` object, a minimum and maximum width and height, and the child must choose a size inside it. `Column`, `Row` and `Box` are all built on the same primitive you use for a custom layout: the `Layout` composable with a `MeasurePolicy`. `MeasurePolicy` is a `fun interface`, so the common form is a trailing lambda: - It receives `measurables`, one per child layout in `content`, and the parent's `constraints`. - It calls `measure(constraints)` on each measurable and gets a `Placeable` with a `width` and `height`. - It returns `layout(width, height) { ... }`, which reports the node's size; inside the block it calls `placeRelative(x, y)` or `place(x, y)` on each placeable. A child that is never placed is not shown. `placeRelative` mirrors the x position in a right-to-left layout direction; `place` does not. For a single element, `Modifier.layout { measurable, constraints -> }` gives the same power without a new composable. ## A worked layout: avatar with a badge that keeps its room Placing a badge with `Box` and `offset` lets it overhang the `Box`'s bounds, so a neighbour can end up under it. A small custom layout reserves the space instead: ```kotlin Layout(content = content, modifier = modifier) { measurables, constraints -> val loose = constraints.copy(minWidth = 0, minHeight = 0) val avatar = measurables[0].measure(loose) val badge = measurables[1].measure(loose) val width = constraints.constrainWidth(avatar.width + badge.width / 2) val height = constraints.constrainHeight(avatar.height + badge.height / 2) layout(width, height) { avatar.placeRelative(0, badge.height / 2) badge.placeRelative(avatar.width - badge.width / 2, 0) } } ``` The children are measured with **loose** constraints, minimums of zero, so a parent's exact size does not force the badge to the avatar's size. The reported size includes half the badge on the top and end sides, and `constrainWidth` and `constrainHeight` keep it inside what the parent allowed. ## Why one measurement per child Compose does **not** permit multi-pass measurement: a layout may measure each child only once per pass. Calling `measure()` twice on the same `Measurable` throws an `IllegalStateException` whose message says so and points to the intrinsic measurement methods. The rule keeps deep nesting cheap. In the View system a parent measuring a child twice, nested several levels deep, multiplied the work at every level, which is why flat hierarchies used to matter. ## Intrinsics: asking before measuring Sometimes a parent needs to know a child's size before it can choose the constraints to measure it with. **Intrinsic measurements** answer that without a second measurement: | Query | Meaning | |---|---| | `minIntrinsicWidth(height)` | the narrowest width at which the content still draws correctly | | `maxIntrinsicWidth(height)` | the width beyond which more width no longer reduces the height | | `minIntrinsicHeight(width)` | the smallest height that draws the content at that width | | `maxIntrinsicHeight(width)` | the height beyond which more height no longer reduces the width | The everyday use is a modifier: `Modifier.height(IntrinsicSize.Min)` on a `Row` makes the row as tall as the tallest child's minimum intrinsic height, so a `VerticalDivider` with `fillMaxHeight()` matches the text beside it instead of stretching to the screen. For your own `Layout`, the default intrinsic methods make a best-effort approximation by reusing your `measure` logic, which is not correct for every layout. When parents will query yours, implement `MeasurePolicy` as an object and override the intrinsic methods it needs; a custom layout modifier overrides the same methods on `LayoutModifier`. ## SubcomposeLayout and BoxWithConstraints: what they cost `SubcomposeLayout` composes children **during** the layout phase, so the content can depend on the incoming constraints. `BoxWithConstraints` is built on it and exposes `maxWidth` and friends to its content. The price: 1. Composition of that content moves into the layout pass, so a change in constraints can recompose it during layout, work a plain `Layout` never does. 2. It does not support intrinsic measurements. Asking for them throws, with a message naming lazy lists, `BoxWithConstraints` and `TabRow` as affected and suggesting a custom layout or a fixed size modifier instead. 3. It invites using constraints for decisions a plain `Layout` could make by measuring. Reach for `BoxWithConstraints` when the **content** must differ by available space, such as two panes versus one. When only sizes and positions differ, a `Layout` is cheaper. ## Pitfalls to name in an interview - Measuring a child a second time to try other constraints instead of using intrinsics. - Passing the parent's exact constraints straight to every child, which forces them all to one size. - Reporting a size outside the incoming constraints; the parent sees it coerced and the child centred, which looks like a misplaced layout. - Forgetting to place a child, which leaves it invisible. - Wrapping `BoxWithConstraints` in an intrinsic-size modifier.
- When would you write Modifier.layout { } instead of a Layout composable in Compose?When you change how one element is measured or placed, not how several children relate. `Modifier.layout { measurable, constraints -> }` wraps a single measurable, for example to position text by its first baseline, which is how `paddingFromBaseline` behaves. To measure and arrange several children you need the `Layout` composable; `Row` and `Column` are built on it.
- Your custom Compose Layout sits inside a Row with Modifier.height(IntrinsicSize.Min) and comes out the wrong height; what do you check?The `Row` asks your layout for `minIntrinsicHeight`, and without an override the default approximates it by reusing your measure logic, which may not match how you really size. Implement `MeasurePolicy` as an object and override `minIntrinsicHeight` (and the other intrinsic methods the parents use) to return what your layout actually needs at a given width.
- A layout can measure a child twice to try different constraints, as Views did.
- Intrinsic measurements secretly measure each child twice.
- The default intrinsics of a custom Layout are always exact.
- BoxWithConstraints is free and supports IntrinsicSize like any Box.
- An unplaced child still draws at position zero.