skip to content

Modifiers & Custom Layouts

Modifier chains where order changes the result, Box, Row and Column, and custom Layout with your own measure policy. Interviewers ask why padding before background differs from padding after it.

on this pageshow

explore

questions

5

In Jetpack Compose, why does Modifier.padding(16.dp).background(Color.Red) render differently from Modifier.background(Color.Red).padding(16.dp)?

level: juniorimportance: must knowfreq 72%

answer

  1. chains nest, they do not merge
  2. the first modifier is the outermost
  3. padding shrinks what comes after it
  4. touch targets obey the same rule

basics

~10 s

Each modifier wraps everything after it. Padding then background insets first, so red fills only the inner area; background then padding paints the whole padded area red, then insets the content.

solid answer

~30 s

A `Modifier` chain is applied outside-in: the first modifier wraps the second, which wraps the next, down to the layout node. With `padding(16.dp).background(Color.Red)`, `padding` is outermost, so `background` paints only the inner content and the 16 dp ring stays transparent. With `background(Color.Red).padding(16.dp)`, `background` wraps the padded node and the red covers the padding too. The same rule sets the touch target: `clickable` before `padding` makes the padding tappable, after it does not. It is also why Compose has no margin modifier: padding placed earlier in the chain acts as a margin.

code

kotlin · 17 lines
kotlin
@Composable
fun ProfileAvatar(
    avatar: Painter,
    onAvatarClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Image(
        painter = avatar,
        contentDescription = "Profile photo",
        modifier = modifier
            .padding(8.dp)
            .size(72.dp)
            .clip(CircleShape)
            .border(2.dp, Color.White, CircleShape)
            .clickable(onClick = onAvatarClick),
    )
}

go deeper

for a junior

Recall that each modifier wraps the ones after it, and be ready to sketch padding-then-background next to background-then-padding on a whiteboard.

for a middle

Explain it through constraints: padding lowers what it passes inward, size modifiers pin the minimum and maximum, and drawing or click modifiers act on the area they wrap.

for a senior

Show you catch order bugs in review: a clip applied to a padded box, a touch target that silently excludes its padding, a size call made useless by an earlier fillMaxSize.

for a principal

Treat order as an API convention: components take one modifier parameter applied first, so callers own outer spacing and size without forking the component.

## What a modifier chain is A **modifier** in Jetpack Compose decorates a composable: size, padding, drawing, clicks, semantics. The chain `Modifier.a().b().c()` is an ordered, immutable list, and Compose turns it into **nested wrappers**: `a` wraps `b`, `b` wraps `c`, and `c` wraps the layout node itself (the `Image`, `Text` or `Column`). Two consequences follow from that picture: - **Constraints flow inward.** The parent's constraints enter the first modifier, and each modifier that cares about size may change them before passing them to the next one. - **Drawing and input are scoped by position.** A modifier acts on the area of everything it wraps. A modifier earlier in the chain wraps more, so it sees a bigger area. So the order of calls is the order of nesting, and nesting is what you see on screen. ## Padding then background, background then padding Take a text whose content is 100 dp wide, with 16 dp of padding: | Chain | What `background` wraps | Result | |---|---|---| | `Modifier.padding(16.dp).background(Color.Red)` | only the 100 dp content | a red box with a transparent 16 dp ring around it | | `Modifier.background(Color.Red).padding(16.dp)` | the padded 132 dp node | red everywhere, content inset by 16 dp | In the first chain `padding` is outermost. It lowers the maximum constraints it passes inward, measures what it wraps, reports a size 32 dp larger on each axis and places its content 16 dp in. `background` sits inside the padding, so it paints only behind the inner content. In the second chain `background` is outermost and paints behind the whole padded node. This is why Compose has **no margin modifier**. Padding placed before a background or a click behaves like a margin; padding placed after it behaves like inner padding. ## Clicks, clips and borders follow the same rule The rule is not special to backgrounds. Every modifier that acts on an area uses the area it wraps. - **`clickable`.** Before `padding`, the padding is part of the touch target. After `padding`, taps on the padding do nothing. - **`clip`.** `clip(CircleShape).padding(10.dp).size(100.dp)` on an image creates a 120 dp circular mask and draws a 100 dp image inside it, so the mask is too big and the image is not round. Put the padding before the clip. - **`border`.** It draws along the bounds it wraps: after padding it hugs the content, before padding it outlines the padded box. ## Size modifiers along the chain Because constraints flow inward, an earlier size modifier limits a later one: 1. `size(100.dp).size(50.dp)` measures at 100 dp. The first `size` sets the minimum and the maximum to exactly 100 dp, and the second must stay inside those bounds, so its 50 dp is coerced to 100 dp. 2. `fillMaxSize().size(50.dp)` fills the parent for the same reason: `fillMaxSize` raised the minimum to the maximum. 3. `fillMaxSize().wrapContentSize().size(50.dp)` gives a 50 dp item centred in the full area. `wrapContentSize` resets the minimum constraints and centres its child in the space it was given. 4. `requiredSize(50.dp)` replaces the incoming constraints instead of adapting to them. The parent sees the child's size as if it were coerced into the parent's constraints, and the child is centred in that space. `offset` is the odd one out: it moves content without changing its measured size, which is what you want for something that should overlap a neighbour. ## A profile avatar, ordered on purpose ```kotlin Modifier .padding(8.dp) // outer gap: not painted, not tappable .size(72.dp) // the avatar is 72 dp .clip(CircleShape) // clip the 72 dp box, not the padded one .border(2.dp, Color.White, CircleShape) // ring on the avatar's edge .clickable(onClick = onAvatarClick) // ripple drawn inside the circle ``` Reading from the top: the 8 dp gap is outside everything, so it is neither clipped, bordered nor clickable. The clip and the border act on the 72 dp box. The click indication is drawn inside the clip, so the ripple stays round. ## Habits that keep chains predictable - Give every component a `modifier: Modifier = Modifier` parameter and apply it to the first element that emits UI, so a caller's padding and size wrap the component from outside. - Read each chain from the top and ask, for every modifier, which area it wraps. - Put `clickable` before the gap you want tappable and after the gap you want inert. - Hoist a fixed chain into a `val` when it does not depend on state; modifiers are data-like objects, and reusing one saves allocations when the composable recomposes often.

  • In Compose, what size does Modifier.size(100.dp).size(50.dp) measure to, and how would you get a centred 50 dp item?
    It measures to 100 dp. The first `size` turns the constraints into exactly 100 dp, and the second must stay inside them, so 50 dp is coerced up. To get 50 dp centred, put `wrapContentSize()` between the two calls, which resets the minimum and centres the child, or use `requiredSize(50.dp)`, which replaces the incoming constraints; the parent then centres the smaller child in its space.
  • Why does an Image with Modifier.clip(CircleShape).padding(10.dp).size(100.dp) come out not quite round?
    `clip` is outermost, so its circular mask is built for the 120 dp padded box. `padding` then insets the image by 10 dp and the image draws at 100 dp inside that bigger circle, so its corners are cut by a circle that does not match it. Moving `padding` before `clip` makes the mask the image's own 100 dp size.

Like naming gift boxes from the outside in: the first box named is the outermost, so a red box named after a spacer box sits inside the gap, while a red box named before the spacer encloses it.

  • Modifier order does not matter; Compose sorts modifiers by type before applying them.
  • Padding always sits inside the background, as in the CSS box model.
  • Compose needs a margin modifier because padding cannot add space outside a background.
  • A later size() call overrides an earlier size() call in the same chain.
  • clickable covers the padding wherever padding appears in the chain.
open as a page

In Jetpack Compose, how do Row's weight, Arrangement and Alignment share out space, and how does Box let a badge overlap an avatar?

level: middleimportance: must knowfreq 60%

basics

~20 s

Row measures unweighted children first, then splits the leftover width by weight; Arrangement spaces children along the main axis and Alignment places them across it. Box stacks children, and BoxScope.align with offset puts a badge over the avatar's corner.

open as a page

In Jetpack Compose, how do you write a custom Layout with its MeasurePolicy, and what stops it from measuring a child twice?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Call 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.

open as a page

In Jetpack Compose, a profile header passes scrollState.value into Modifier.offset(y = ...) and recomposes every scroll frame; how do lambda modifiers fix it?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Compose reruns work from the phase that read a state. Reading the scroll inside Modifier.offset { } defers it to placement, and graphicsLayer { } or drawBehind { } defer alpha or colour, so scrolling stops recomposing.

open as a page

In Jetpack Compose, why write a custom modifier with Modifier.Node and ModifierNodeElement rather than Modifier.composed or a @Composable modifier factory?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

Modifier.Node is the API Compose's own modifiers use: a stateless ModifierNodeElement creates or updates a long-lived node, nothing runs in composition, and only the affected phase is invalidated. Composable factories never skip and composed { } is no longer recommended.

open as a page