skip to content

An Android news article screen built from deeply nested LinearLayouts with layout_weight is slow to lay out; how do the View measure and layout passes explain it, and what would you change?

level: seniorimportance: should knowfreq 44%

answer

  1. two top-down passes before drawing
  2. MeasureSpec modes from parent to child
  3. a parent may measure twice
  4. flatten into one ConstraintLayout

basics

~20 s

Views are measured, then laid out, top-down before drawing. A weighted LinearLayout may measure its children twice, and nesting compounds that work. Flattening the screen into one ConstraintLayout with 0dp constraints and weighted chains cuts that repeated work.

solid answer

~40 s

Before drawing, the framework runs a **measure pass** (`measure()` calling each view's `onMeasure()`) and a **layout pass** (`layout()` calling `onLayout()`), both top-down. Parents push constraints down as `MeasureSpec` values in `EXACTLY`, `AT_MOST` or `UNSPECIFIED` mode, and a parent may measure a child more than once: a `LinearLayout` distributing `layout_weight` measures its children, then measures them again to share the leftover space. Nest weighted layouts and each level repeats the work of the level below, so cost grows with depth, and any `requestLayout()` re-runs it. The fix is a flatter tree: one `ConstraintLayout` from Jetpack, with `0dp` (match constraints) widths, weighted chains instead of weights, and guidelines or barriers for alignment. Use `invalidate()` rather than `requestLayout()` when only pixels change.

code

xml · 27 lines
xml
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp">

    <ImageView
        android:id="@+id/thumbnail"
        android:layout_width="0dp"
        android:layout_height="96dp"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toStartOf="@id/headline"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/headline"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        android:textSize="18sp"
        app:layout_constraintHorizontal_weight="2"
        app:layout_constraintStart_toEndOf="@id/thumbnail"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

go deeper

for a junior

Recall the three stages, measure, layout and draw, and that ConstraintLayout exists to keep layouts flat.

for a middle

Explain MeasureSpec modes, LayoutParams, and why a weighted LinearLayout may measure its children twice.

for a senior

Diagnose a slow screen from its hierarchy, flatten it with chains, guidelines and barriers, and stop needless requestLayout() calls, proving the gain with measurements.

for a principal

Weigh rewriting legacy View screens against migrating them to Compose, and set layout review rules (depth, weights, custom onMeasure) for the team.

## How the View system gets pixels on screen When an activity's window needs a frame, the framework walks the view tree from its root in three stages: 1. **Measure.** `measure(int, int)` is called top-down. Each view works out its size in `onMeasure()` and records it with `setMeasuredDimension()`; afterwards `getMeasuredWidth()` and `getMeasuredHeight()` hold the result. 2. **Layout.** `layout(...)` is called top-down again. Each parent places its children in `onLayout()` using the sizes measured before. 3. **Draw.** Views that intersect the invalid region draw in tree order, parents before (behind) children. `measure()` is `final`; custom behaviour goes in `onMeasure()` and `onLayout()`, which the framework calls for you. ## How parents constrain children Two objects carry the conversation: - **`ViewGroup.LayoutParams`** is how a child states what it wants: an exact size, `MATCH_PARENT` or `WRAP_CONTENT`. - **`MeasureSpec`** is how a parent states what it allows, in one of three modes: | Mode | Meaning for the child | |---|---| | `EXACTLY` | Use exactly this size | | `AT_MOST` | Be any size up to this one | | `UNSPECIFIED` | Say how big you want to be; there is no limit | The documentation notes that **a parent might call `measure()` more than once** on a child. The standard example is a parent that first measures children with unspecified sizes to learn their preferred sizes and then, if the total is too big or too small, measures them again with constraints. A `LinearLayout` sharing leftover space by `layout_weight` behaves this way. ## Why depth and weights cost One extra measure per level is cheap. The trouble is **nesting**: when a weighted `LinearLayout` re-measures a child that is itself a weighted `LinearLayout`, that child re-measures its own children each time it is measured. The repeated work compounds with every level of nesting, and an article screen with headline, byline, image and tag rows built from nested horizontal and vertical layouts can spend a large share of a frame in measure. Every `requestLayout()` (a text change in a `wrap_content` view, an image arriving) re-runs measure and layout up the tree, so the cost is paid again during use, not only at inflation. ## Flattening with ConstraintLayout `ConstraintLayout`, from the Jetpack ConstraintLayout library, positions every child relative to the parent, to siblings or to invisible helpers, so complex screens become **one flat level**: - **Constraints.** Each view needs at least one horizontal and one vertical constraint; a view with none is drawn at the top-left corner on a device, even if the Layout Editor shows it elsewhere. - **Match constraints.** `match_parent` is not supported for children; set the dimension to `0dp` so the view stretches between its constraints, and limit it with `layout_constraintWidth_min` or `_max`. - **Chains** link views with two-way constraints and replace `LinearLayout` rows; in a spread chain, `0dp` views share space by `layout_constraintHorizontal_weight`. - **Guidelines** are invisible lines at a fixed offset or percentage. - **Barriers** move to the far edge of a group of views (set with `barrierDirection`), so a column of labels of unknown width can push a column of values. - **Bias** shifts a view between two opposing constraints (50% by default). For Arabic and other right-to-left locales, constrain to `start` and `end` rather than `left` and `right`; with `android:supportsRtl="true"` the same layout mirrors. A typical rewrite of the article screen goes in this order: 1. List what each nested layout exists for: a row, a column, a weighted split, or only padding. 2. Replace each weighted row with a chain of `0dp` views and the matching weights. 3. Replace label and value columns with a barrier, and fixed splits with a guideline. 4. Move padding-only wrappers into margins on the children. 5. Compare frame timing before and after on a low-end device. ## Keeping the passes cheap after the fix - Call **`invalidate()`** when only appearance changes (colour, progress); it schedules a draw without re-measuring. Call **`requestLayout()`** only when size or position can change. - In a custom view, override **`onMeasure()`** to respect the incoming `MeasureSpec` and always call `setMeasuredDimension()`; skipping it throws at measure time. - Avoid allocating objects in `onDraw()`, which can run every frame. - Measure before and after with the IDE's layout and frame profiling tools, which are covered with Android Studio, rather than assuming the flatter tree helped.

  • What happens if a custom View's onMeasure() never calls setMeasuredDimension()?
    The framework throws an exception at measure time, because `measure()` checks that the measured size was recorded. Every `onMeasure()` override must end by calling `setMeasuredDimension()` with a size that respects the incoming `MeasureSpec`, often via `resolveSize()`.
  • A ConstraintLayout child looks right in the Layout Editor but appears at the top-left on a device. Why?
    It is missing a constraint on one axis. The editor keeps a dropped view where you left it for convenience, but at runtime a view with no constraint on an axis sits at 0 on that axis. Add at least one horizontal and one vertical constraint.

  • Each view is measured exactly once per frame, whatever its parent.
  • Nesting depth only costs memory, never measure time.
  • match_parent is the right way to stretch a ConstraintLayout child.
  • requestLayout() and invalidate() do the same work.
  • A view without constraints stays where the Layout Editor shows it.