Custom layouts and modifiers
Why it matters
Row,ColumnandBoxcover most screens, but flow-like tag lists, overlapping avatars or charts with labels need a customLayout. Knowing the measure and place contract lets you build them without hacks.- Senior Android interviews often ask you to sketch a custom
LayoutorModifier.Node, and to explainConstraints, why each child is measured once, andplacevsplaceRelative. Modifier.Nodeis the API Google recommends for custom modifiers.Modifier.composed { }is no longer recommended because of its performance cost.- Lambda modifiers such as
Modifier.layout { },offset { }anddrawBehind { }read state in the layout or draw phase, so a fast-changing value does not force recomposition.
The simple explanation
- A layout is a stage manager. The theatre tells it how much space it may use (
Constraints). - It asks each actor (child) to get ready within some limits (measure). Each actor answers once with its size (
Placeable). - The manager picks its own size within the theatre's limits, then tells each actor where to stand (place).
- A modifier node is a small helper attached to one actor, kept between scenes and updated rather than replaced.
How do you make a custom layout in Jetpack Compose? Call the Layout composable with your content and a MeasurePolicy lambda. The lambda receives the children as List<Measurable> and the parent's Constraints. Measure each child once with measurable.measure(childConstraints) to get a Placeable, choose your own size within the incoming constraints, then call layout(width, height) { ... } and position each child with placeable.placeRelative(x, y).
Constraints carry minWidth, maxWidth, minHeight and maxHeight in pixels. They flow down (parent to child) and sizes flow up (child to parent). maxWidth can be Constraints.Infinity, for example inside a horizontally scrolling container. A layout should report a size inside its incoming constraints; if it does not, Compose coerces the size and centers the content in the allowed space.
Measure once. Compose measures a child at most once per measure pass. Calling measure twice on the same Measurable throws an exception. If you need a child's size before measuring others, use intrinsic measurements (minIntrinsicWidth and friends) or SubcomposeLayout.
Placement. placeRelative mirrors the x position in right-to-left layout direction; place does not. Use placeRelative unless the position must stay fixed on screen in every locale.
Custom modifiers with Modifier.Node. A node-based modifier has three parts:
| Part | Role |
|---|---|
Factory function, such as fun Modifier.uniformPadding(all: Dp) | Public API; chains an element with this then Element(...) |
ModifierNodeElement<N> (usually a data class) | Lightweight, compared with equals; create() builds the node, update() changes it |
Modifier.Node() subclass implementing LayoutModifierNode, DrawModifierNode, PointerInputModifierNode and so on | Long-lived object that does the work and survives recomposition |
When the modifier chain recomposes with an equal element, nothing happens. With a different element, update() is called on the existing node instead of creating a new one.
Notes
Layout(content, modifier) { measurables, constraints -> ... }is the basic custom layout.Row,ColumnandBoxare built on the same idea.- Pass children constraints derived from yours. A common start is
constraints.copy(minWidth = 0, minHeight = 0), so children can be smaller than the parent's minimum. - Report a size inside the incoming constraints, for example
width.coerceIn(constraints.minWidth, constraints.maxWidth). - Calling
measuretwice on the sameMeasurablein one pass throws. Use intrinsics orSubcomposeLayoutwhen a child's size must drive another child's constraints. placeRelativemirrors x in RTL;placenever mirrors. UseplaceRelativeby default.- For a one-off change to how a single element is measured,
Modifier.layout { measurable, constraints -> ... }is simpler than a full node. Modifier.Nodeis the recommended way to write custom modifiers. ImplementLayoutModifierNodeto change measurement or placement,DrawModifierNodeto draw, and combine interfaces when needed.Modifier.composed { }is no longer recommended. It runs composition work for every element it is used on and cannot be skipped like a node.- The
ModifierNodeElementmust implementequalsandhashCode(adata classdoes this). That is how Compose knows whenupdate()is needed. - If a node's property changes outside
update(), callinvalidateMeasurement()orinvalidateDraw()so Compose re-runs the right phase. - Do not put a
LazyColumninside aColumnwithverticalScroll: the lazy list gets an infinite max height and throws. Use oneLazyColumnwith severalitemblocks instead.
Code example
A CenteredColumn layout that stacks children and centers each one horizontally, and a uniformPadding modifier written with Modifier.Node.
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.node.LayoutModifierNode
import androidx.compose.ui.node.ModifierNodeElement
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.offset
@Composable
fun CenteredColumn(
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
Layout(content = content, modifier = modifier) { measurables, constraints ->
// Children may be smaller than our minimum size
val childConstraints = constraints.copy(minWidth = 0, minHeight = 0)
// Measure each child exactly once
val placeables = measurables.map { it.measure(childConstraints) }
val width = (placeables.maxOfOrNull { it.width } ?: 0)
.coerceIn(constraints.minWidth, constraints.maxWidth)
val height = placeables.sumOf { it.height }
.coerceIn(constraints.minHeight, constraints.maxHeight)
layout(width, height) {
var y = 0
placeables.forEach { placeable ->
placeable.placeRelative(x = (width - placeable.width) / 2, y = y)
y += placeable.height
}
}
}
}
// Public API
fun Modifier.uniformPadding(all: Dp): Modifier = this then UniformPaddingElement(all)
// Element: cheap, compared with equals; creates or updates the node
private data class UniformPaddingElement(val all: Dp) : ModifierNodeElement<UniformPaddingNode>() {
override fun create() = UniformPaddingNode(all)
override fun update(node: UniformPaddingNode) {
node.all = all
}
}
// Node: survives recomposition and does the measuring
private class UniformPaddingNode(var all: Dp) : Modifier.Node(), LayoutModifierNode {
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints,
): MeasureResult {
val pad = all.roundToPx()
// Shrink the space available to the content by the padding on both sides
val placeable = measurable.measure(constraints.offset(-pad * 2, -pad * 2))
val width = (placeable.width + pad * 2).coerceIn(constraints.minWidth, constraints.maxWidth)
val height = (placeable.height + pad * 2).coerceIn(constraints.minHeight, constraints.maxHeight)
return layout(width, height) {
placeable.placeRelative(pad, pad)
}
}
}CenteredColumnmeasures every child once, picks a size inside the incoming constraints, and usesplaceRelativeso placement is RTL-aware. Each child gets the full max height, so a real column would also handle content taller than the parent (scrolling or weights).UniformPaddingElementis adata class, soModifier.uniformPadding(16.dp)on a recomposition is equal to the previous element and the node is left alone. A new value callsupdate()on the same node.- Changing
allinupdate()re-measures automatically, because nodes invalidate themselves afterupdate()by default. Constraints.offsetsubtracts the padding and never goes below zero, so the content cannot be given negative space.
Run the idea in plain Kotlin
A model of the measure and place contract: constraints coerce sizes, each child can be measured only once, and placeRelative mirrors x in RTL. This version aligns children to the start so the mirroring is visible.
data class Constraints(val minWidth: Int, val maxWidth: Int, val minHeight: Int, val maxHeight: Int)
class Placeable(val name: String, val width: Int, val height: Int)
class Measurable(private val name: String, private val wantWidth: Int, private val wantHeight: Int) {
private var measured = false
fun measure(c: Constraints): Placeable {
check(!measured) { name + " measured twice" }
measured = true
return Placeable(
name,
wantWidth.coerceIn(c.minWidth, c.maxWidth),
wantHeight.coerceIn(c.minHeight, c.maxHeight)
)
}
}
fun children() = listOf(Measurable("A", 100, 50), Measurable("B", 400, 80), Measurable("C", 150, 60))
fun startColumn(kids: List<Measurable>, c: Constraints, rtl: Boolean) {
val placeables = kids.map { it.measure(c.copy(minWidth = 0, minHeight = 0)) }
val width = (placeables.maxOfOrNull { it.width } ?: 0).coerceIn(c.minWidth, c.maxWidth)
val height = placeables.sumOf { it.height }.coerceIn(c.minHeight, c.maxHeight)
println((if (rtl) "RTL" else "LTR") + " layout size: " + width + "x" + height)
var y = 0
for (p in placeables) {
val x = 0 // start edge
val screenX = if (rtl) width - p.width - x else x // what placeRelative does
println(" " + p.name + " (" + p.width + "x" + p.height + ") at x=" + screenX + ", y=" + y)
y += p.height
}
}
fun main() {
val constraints = Constraints(minWidth = 0, maxWidth = 300, minHeight = 0, maxHeight = 200)
startColumn(children(), constraints, rtl = false)
startColumn(children(), constraints, rtl = true)
val a = children().first()
a.measure(constraints)
try {
a.measure(constraints)
} catch (e: IllegalStateException) {
println("Error: " + e.message)
}
}Expected output:
LTR layout size: 300x190
A (100x50) at x=0, y=0
B (300x80) at x=0, y=50
C (150x60) at x=0, y=130
RTL layout size: 300x190
A (100x50) at x=200, y=0
B (300x80) at x=0, y=50
C (150x60) at x=150, y=130
Error: A measured twice
In production
- A custom chart layout measured its bars, then tried to measure the axis labels again with constraints based on the bar width.
- The second
measurecall on the same children threw anIllegalStateExceptionin a debug build as soon as the screen opened. - The developer had tried to "measure, look at the size, then measure properly", which the layout contract does not allow.
- The layout asks the labels for
maxIntrinsicWidth(constraints.maxHeight)first, which does not count as measuring, and then measures every child once with the right constraints. - For a variant where the labels' content depended on the measured bar width, the team switched to
SubcomposeLayout, which composes the labels only after the bars are measured. - A screenshot test with two locales, one RTL, guards the label positions.
- A loading shimmer was written as
fun Modifier.shimmer() = composed { ... }usingrememberInfiniteTransitioninside. - Every placeholder row ran its own composition work for the modifier, and the list stuttered while scrolling through many placeholders.
- The modifier was rewritten as a
ModifierNodeElementplus aModifier.NodeimplementingDrawModifierNode. The node starts its animation inonAttach()using itscoroutineScopeand callsinvalidateDraw()on each frame, so only the draw phase runs. - The element is a
data classwith the colors as properties, so recomposing the row with the same colors does no modifier work. - A Macrobenchmark scroll test of the loading state showed fewer slow frames, and the team kept that test.
Common mistakes
- Measuring a child twice. It throws at runtime. Measure each
Measurableonce; use intrinsics orSubcomposeLayoutwhen one child's size must drive another's constraints. - Passing your constraints straight through when the parent has a minimum. If the parent's
minWidthis 300, every child is forced to at least 300. Relax the minimums withconstraints.copy(minWidth = 0, minHeight = 0)when children should keep their own size. - Reporting a size outside the incoming constraints. Compose coerces it and centers your content, which looks like a mysterious offset. Use
coerceInwith the constraints. - Using
placefor start-aligned content. It does not mirror in RTL, so content sticks to the left in Arabic or Hebrew. UseplaceRelative. - Writing new custom modifiers with
composed { }. It is no longer recommended for performance reasons. UseModifier.Node, or chain existing modifiers in a plain function when you need no state. - Making the element a regular class without
equals. Every recomposition then looks like a new element and callsupdate(). Use adata classor implementequalsandhashCode. - Nesting a
LazyColumnin a vertically scrollingColumn. The lazy list is measured with infinite height and throws. Put all content into oneLazyColumn.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you build a custom layout in Jetpack Compose?”
“Why is Modifier.Node preferred over Modifier.composed?”
“What do Constraints mean, and what happens if a layout ignores them?”
“What is the difference between place and placeRelative?”
Quiz
In a MeasurePolicy you need a child's size before deciding another child's constraints. What should you do?
Why does Google recommend Modifier.Node over Modifier.composed for new custom modifiers?
A layout reports a width larger than constraints.maxWidth. What happens?
What does placeRelative do differently from place?
0 of 4 answered
Mini task
Build a CenteredRow and a node-based modifier (25 min)
- Write the layout. Create
@Composable fun CenteredRow(modifier: Modifier = Modifier, content: @Composable () -> Unit)withLayout. Place children side by side, each centered vertically within the row's height. Measure each child once with relaxed minimum constraints. - Respect constraints. Coerce the row's width and height into the incoming constraints with
coerceIn. - Write a modifier node. Create
fun Modifier.dashedBorder(color: Color)with adata class DashedBorderElement(val color: Color) : ModifierNodeElement<DashedBorderNode>()and aDashedBorderNode(var color: Color) : Modifier.Node(), DrawModifierNodethat callsdrawContent()and then draws a dashed rectangle withdrawRect(color, style = Stroke(width = 2f, pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f)))). - Check update. Add a log line in
create()and inupdate(). Toggle the border color with a button and confirmcreate()runs once andupdate()runs on each color change. - Check RTL. Wrap a preview in
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl)and confirm children are mirrored.
Done condition: the row centers its children vertically, the border redraws on color change without create() being called again, and the RTL preview mirrors the order of the children.