Custom layouts and modifiers

Learn to build custom layouts in Jetpack Compose with Layout, MeasurePolicy and Constraints, and write custom modifiers with Modifier.Node instead of composed. About 25 minutes.

Why it matters

  • Row, Column and Box cover most screens, but flow-like tag lists, overlapping avatars or charts with labels need a custom Layout. Knowing the measure and place contract lets you build them without hacks.
  • Senior Android interviews often ask you to sketch a custom Layout or Modifier.Node, and to explain Constraints, why each child is measured once, and place vs placeRelative.
  • Modifier.Node is 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 { } and drawBehind { } 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:

PartRole
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 onLong-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, Column and Box are 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 measure twice on the same Measurable in one pass throws. Use intrinsics or SubcomposeLayout when a child's size must drive another child's constraints.
  • placeRelative mirrors x in RTL; place never mirrors. Use placeRelative by default.
  • For a one-off change to how a single element is measured, Modifier.layout { measurable, constraints -> ... } is simpler than a full node.
  • Modifier.Node is the recommended way to write custom modifiers. Implement LayoutModifierNode to change measurement or placement, DrawModifierNode to 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 ModifierNodeElement must implement equals and hashCode (a data class does this). That is how Compose knows when update() is needed.
  • If a node's property changes outside update(), call invalidateMeasurement() or invalidateDraw() so Compose re-runs the right phase.
  • Do not put a LazyColumn inside a Column with verticalScroll: the lazy list gets an infinite max height and throws. Use one LazyColumn with several item blocks 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)
        }
    }
}
  • CenteredColumn measures every child once, picks a size inside the incoming constraints, and uses placeRelative so 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).
  • UniformPaddingElement is a data class, so Modifier.uniformPadding(16.dp) on a recomposition is equal to the previous element and the node is left alone. A new value calls update() on the same node.
  • Changing all in update() re-measures automatically, because nodes invalidate themselves after update() by default.
  • Constraints.offset subtracts 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

Chart labels needed the bar width before measuring
  • A custom chart layout measured its bars, then tried to measure the axis labels again with constraints based on the bar width.
  • The second measure call on the same children threw an IllegalStateException in 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 fix
  • 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 shimmer modifier was slow in long lists
  • A loading shimmer was written as fun Modifier.shimmer() = composed { ... } using rememberInfiniteTransition inside.
  • Every placeholder row ran its own composition work for the modifier, and the list stuttered while scrolling through many placeholders.
The fix
  • The modifier was rewritten as a ModifierNodeElement plus a Modifier.Node implementing DrawModifierNode. The node starts its animation in onAttach() using its coroutineScope and calls invalidateDraw() on each frame, so only the draw phase runs.
  • The element is a data class with 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 Measurable once; use intrinsics or SubcomposeLayout when one child's size must drive another's constraints.
  • Passing your constraints straight through when the parent has a minimum. If the parent's minWidth is 300, every child is forced to at least 300. Relax the minimums with constraints.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 coerceIn with the constraints.
  • Using place for start-aligned content. It does not mirror in RTL, so content sticks to the left in Arabic or Hebrew. Use placeRelative.
  • Writing new custom modifiers with composed { }. It is no longer recommended for performance reasons. Use Modifier.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 calls update(). Use a data class or implement equals and hashCode.
  • Nesting a LazyColumn in a vertically scrolling Column. The lazy list is measured with infinite height and throws. Put all content into one LazyColumn.

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)

  1. Write the layout. Create @Composable fun CenteredRow(modifier: Modifier = Modifier, content: @Composable () -> Unit) with Layout. Place children side by side, each centered vertically within the row's height. Measure each child once with relaxed minimum constraints.
  2. Respect constraints. Coerce the row's width and height into the incoming constraints with coerceIn.
  3. Write a modifier node. Create fun Modifier.dashedBorder(color: Color) with a data class DashedBorderElement(val color: Color) : ModifierNodeElement<DashedBorderNode>() and a DashedBorderNode(var color: Color) : Modifier.Node(), DrawModifierNode that calls drawContent() and then draws a dashed rectangle with drawRect(color, style = Stroke(width = 2f, pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f)))).
  4. Check update. Add a log line in create() and in update(). Toggle the border color with a button and confirm create() runs once and update() runs on each color change.
  5. 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.

Next: Animations in depth