Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 104 ยท Legacy Views

XML Layouts: LinearLayout, ConstraintLayout and More

Learn the classic Android XML layouts: LinearLayout and layout_weight, FrameLayout, RelativeLayout, ConstraintLayout chains and guidelines, MotionLayout, and Compose equivalents.

Before Compose, every Android screen was an XML file under res/layout/. The root element is a layout (a ViewGroup) that decides where its children go and how big they are. Millions of apps still ship with these files, so reading and editing them is a core Android skill, even if you build new screens in Compose.

This lesson tours the layouts you will meet: LinearLayout, FrameLayout, RelativeLayout, ConstraintLayout and MotionLayout. For each one you will see the XML, what it does and the Compose code that replaces it. The XML is read-only because layouts need the Android SDK to be inflated. The TryIts are plain Kotlin stand-ins that run the layout math, so you can watch how layout_weight and chains share space. For a first look at XML attributes, see Views Interop and Legacy XML.

Sizes, dp and sp

Every view needs a layout_width and a layout_height. There are three kinds of values:

  • match_parent: as large as the parent allows.
  • wrap_content: just big enough for the content.
  • A fixed size such as 48dp.

dp (density-independent pixels) keeps a size physically similar across screens: 1 dp is one pixel on a 160 dpi screen and scales up on denser ones. sp (scale-independent pixels) works the same way but also follows the user's font-size setting, so use sp for text and dp for everything else. Compose uses the same units (16.dp, 16.sp). Never use raw px in a layout.

Two spacing attributes confuse beginners: padding is space inside the view's border, layout_margin is space outside it, between the view and its neighbors.

LinearLayout

LinearLayout places children one after another in a single direction, set by android:orientation (vertical or horizontal). It is the ancestor of Column and Row.

XML
<!-- read-only example: res/layout/row_item.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:padding="16dp">

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/ic_person" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginStart="12dp"
        android:text="@string/user_name" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/follow" />
</LinearLayout>

gravity aligns the children inside the layout; layout_gravity aligns one view inside its parent. Both are common sources of "why is it not centered?" bugs.

layout_weight

layout_weight shares the leftover space among children. The usual recipe is: set the size in the layout direction to 0dp and give each child a weight. A view with weight 2 gets twice the leftover space of a view with weight 1. Without the 0dp, the view's own size is added first and the result surprises you.

In Compose this is Modifier.weight(1f) inside a Row or Column. The stand-in computes what the framework does: subtract the fixed sizes, then split what remains in proportion to the weights.

Kotlin How layout_weight shares space (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The icon and button keep their fixed sizes; the 280 dp that remain are split 1 : 2, so the title gets about 93 dp and the subtitle about 187 dp.

FrameLayout

FrameLayout stacks its children on top of each other, with the first at the bottom. Each child can be placed with layout_gravity. It is the ancestor of Box, and it is the cheapest layout, so it is used for overlays (a badge on an avatar, a progress bar over a list) and as the container into which fragments are placed.

XML
<!-- read-only example -->
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/cover" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|start"
        android:layout_margin="16dp"
        android:text="@string/title"
        android:textColor="@android:color/white" />
</FrameLayout>

RelativeLayout (legacy)

RelativeLayout places a view relative to its siblings or its parent: layout_below, layout_toEndOf, layout_alignParentEnd, layout_centerInParent. It was the flexible layout of the early years. You will find it in old code, but you should not start new screens with it: it measures children twice, it cannot express many relationships (chains, ratios, bias), and ConstraintLayout does everything it does with a flat hierarchy. When you maintain an old RelativeLayout, a small edit is fine. Android Studio can also convert it for you (right-click the layout in the Component Tree and choose Convert to ConstraintLayout).

Deeply nested layouts are slow because each level adds a measuring pass. Prefer a flat hierarchy: that is the main reason ConstraintLayout exists.

ConstraintLayout

ConstraintLayout (a Jetpack library: androidx.constraintlayout:constraintlayout) is the default layout in Android Studio templates for XML screens. Every child needs at least one horizontal and one vertical constraint that ties an edge to the parent, a sibling or a guideline. A view with no constraints is drawn at the top-left corner and Android Studio flags it.

XML
<!-- read-only example: res/layout/profile_header.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/avatar"
        android:layout_width="64dp"
        android:layout_height="64dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"
        app:layout_constraintStart_toEndOf="@id/avatar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@id/avatar"
        android:text="@string/user_name" />

    <TextView
        android:id="@+id/handle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="@id/name"
        app:layout_constraintEnd_toEndOf="@id/name"
        app:layout_constraintTop_toBottomOf="@id/name"
        android:text="@string/user_handle" />
</androidx.constraintlayout.widget.ConstraintLayout>

Read the attribute names as sentences: layout_constraintStart_toEndOf="@id/avatar" means "my start edge is attached to the end edge of avatar". Some details worth knowing:

  • 0dp in a constrained direction means match constraints: fill the space between the two constraints. It replaces match_parent inside a ConstraintLayout.
  • If a view is constrained on both sides, it is centered between them. layout_constraintHorizontal_bias (0 to 1) moves it away from the middle.
  • layout_constraintDimensionRatio="16:9" keeps an aspect ratio (with one dimension at 0dp).
  • layout_constraintBaseline_toBaselineOf aligns the text baselines of two views.
  • Group hides or shows several views by id with one attribute; Placeholder and Flow helpers exist too.

Chains

A chain is a set of views linked to each other in both directions along one axis. The first view of the chain (the "head") controls it with layout_constraintHorizontal_chainStyle:

  • spread (default): views are spread evenly with equal gaps.
  • spread_inside: the first and last views touch the edges, the rest are spaced out between them.
  • packed: the views are grouped together and centered (use bias to move the group).

Combined with layout_constraintHorizontal_weight on views that have 0dp width, a chain behaves like a LinearLayout with weights, but without nesting.

Guidelines and barriers

A Guideline is an invisible line placed at a percentage (layout_constraintGuide_percent="0.3") or a fixed offset (layout_constraintGuide_begin="24dp"). Views can constrain themselves to it, which is useful for a two-column form whose columns line up everywhere.

A Barrier is an invisible wall that sits at the farthest edge of a group of views (app:barrierDirection="end" and app:constraint_referenced_ids="label1,label2"). If the labels have different lengths in different languages, the barrier moves with the longest one and the fields start after it. That is a problem a guideline cannot solve.

XML
<!-- read-only example -->
<androidx.constraintlayout.widget.Barrier
    android:id="@+id/labelsBarrier"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:barrierDirection="end"
    app:constraint_referenced_ids="emailLabel,passwordLabel" />

Modern Android Studio has a Layout Editor with a Design and a Code view, a Component Tree, and an Attributes panel. Use it to draw constraints, then read the generated XML, as it is what your teammates review.

The stand-in below resolves the three chain styles on a 360 dp wide row, so you can see the difference in numbers.

Kotlin Chain styles on a 360 dp row (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

MotionLayout

MotionLayout is a subclass of ConstraintLayout that animates between constraint sets. You describe a start state and an end state (two sets of constraints) and a transition, and it moves every view between them as the user drags, swipes or presses a button. Typical uses are collapsing headers, animated cards and onboarding screens. A MotionScene XML file holds ConstraintSet, Transition, OnSwipe and KeyFrameSet elements, and the Android Studio Motion Editor can create them visually.

XML
<!-- read-only example: res/xml/scene_header.xml (outline) -->
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:constraintSetStart="@id/expanded"
        motion:constraintSetEnd="@id/collapsed"
        motion:duration="400">
        <OnSwipe
            motion:touchAnchorId="@id/list"
            motion:touchAnchorSide="top"
            motion:dragDirection="dragUp" />
    </Transition>

    <ConstraintSet android:id="@+id/expanded"> <!-- sizes and positions --> </ConstraintSet>
    <ConstraintSet android:id="@+id/collapsed"> <!-- smaller header --> </ConstraintSet>
</MotionScene>

In new Compose code you do not need it: AnimatedVisibility, animate*AsState, Modifier.nestedScroll for collapsing bars, and MotionLayout for Compose (in the constraintlayout-compose library) cover the same ground. See Animation in Compose.

XML layouts versus Compose

XML layouts and their Compose twins

LinearLayout Column and Row
FrameLayout Box
ConstraintLayout ConstraintLayout for Compose, or Row/Column/Box
layout_weight Modifier.weight

Compose has no separate layout files: a layout is just a function.

1 / 2

The same profile header as the XML above looks like this in Compose. Notice that Row, Column and weight are enough, with no constraint IDs:

Kotlin
// read-only example
@Composable
fun ProfileHeader(name: String, handle: String) {
    Row(Modifier.fillMaxWidth().padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
        Image(painterResource(R.drawable.ic_person), contentDescription = null, Modifier.size(64.dp))
        Column(Modifier.weight(1f).padding(start = 12.dp)) {
            Text(name)
            Text(handle)
        }
    }
}

When a layout is truly complicated, Compose also has ConstraintLayout (androidx.constraintlayout:constraintlayout-compose) with createRef(), constrainAs and createHorizontalChain, which mirrors everything above. See Layouts: Row, Column and Box for the native Compose layouts.

The second stand-in is a tiny solver for ratio and bias: it shows how a view constrained on both sides is placed with a bias, and how layout_constraintDimensionRatio derives the height.

Kotlin Bias and dimension ratio (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Common mistakes

  • Using match_parent inside ConstraintLayout. Use 0dp (match constraints) with constraints on both sides.
  • Forgetting one axis. A view with only a horizontal constraint jumps to the top; Studio warns you.
  • layout_weight without 0dp. The view keeps its own size and the weights split the wrong amount.
  • Deep nesting of LinearLayouts to build a grid. Use ConstraintLayout or GridLayout, or in Compose a LazyVerticalGrid.
  • Text in dp. Use sp for text sizes so the user's font setting works.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which unit should you use for text sizes in an XML layout?

    sp scales with the user's font-size setting as well as the screen density, so it is the right unit for text. Use dp for everything else.
  2. 2. A LinearLayout with a horizontal orientation has two children with layout_width=0dp and layout_weight 1 and 3. How is the leftover space shared?

    The leftover space is divided in proportion to the weights: 1 out of 4 parts and 3 out of 4 parts.
  3. 3. What does a Barrier in ConstraintLayout do?

    A barrier moves with the largest view in its group, so views placed after it never overlap longer labels.
  4. 4. Which Compose construct replaces layout_weight?

    Modifier.weight is available in the RowScope and ColumnScope and shares the remaining space in proportion, like layout_weight.
  5. 5. Why is RelativeLayout discouraged for new screens?

    RelativeLayout still works, but ConstraintLayout covers its features and more (chains, ratios, bias) and measures more efficiently.

Summary

  • A layout XML file describes a tree of Views; each child needs a width and a height (match_parent, wrap_content or a dp value). Use sp for text.
  • LinearLayout stacks in one direction and shares leftover space with layout_weight (use 0dp); FrameLayout stacks children on top of each other.
  • RelativeLayout is legacy; prefer ConstraintLayout.
  • ConstraintLayout needs a horizontal and a vertical constraint per view and offers bias, ratio, chains, guidelines and barriers on a flat hierarchy.
  • MotionLayout animates between constraint sets; in Compose use animation APIs.
  • In Compose, Row, Column, Box and Modifier.weight replace most of these layouts.

Next: Classic Views and Widgets