Collapsing Toolbar Image: 5 Steps for Android Apps

Collapsing Toolbar Image: 5 Steps for Android Apps - Image

This pattern of Collapsing Toolbar Layout is a popular scrolling technique. In familiar terms, you can see this on several apps with a profile detail screen. Android CollapsingToolbarLayout is a wrapper for Toolbar which implements a collapsing app bar. It is designed to be used as a direct child of an AppBarLayout.

How a Collapsing Toolbar Image Header Works

A collapsing toolbar image combines a large visual header with a toolbar that stays useful as the page scrolls. The image occupies the expanded area, while the toolbar and title transition into a compact app bar. In Android, the CollapsingToolbarLayout works with its parent AppBarLayout and a scrolling content view to coordinate that movement.

Think of the collapsing toolbar image as two visual states of one screen, not as an image that simply shrinks. The expanded state gives the page a distinctive introduction; the collapsed state should still provide a clear title and reachable navigation. Choose the image, title placement, scrim, and scroll behavior together so the transition remains readable and predictable.

You can see the Toolbar dynamically changes color, depending on the image. It takes on the most dominant color present in the image. This is a scrolling technique that supports an image header with a scrollable view below it.

This layout consists of:

  • Collapsing Title: The title is larger when the layout is expanded. The text size becomes smaller as the layout is collapsed and scrolled off the screen.
  • app:layout_scrollFlags: The scroll flags of this layout is typically set to “scroll|exitUntilCollapsed”.
  • app:collapsedTitleGravity: Specifies the gravity of title in the container when collapsed.
  • app:contentScrim: This requires specifying a drawable or color value of the CollapsingToolbarLayouts content when it has been scrolled sufficiently off screen eg. ?attr/colorPrimary.
  • app:scrimAnimationDuration: Specifies the duration used for scrim visibility animations. This requires an integer value.

Getting Started

Start by adding the Design Support Library to your app/build.gradle file.

dependencies { 
    … 
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
}

Layout Structure

As always, we’ll get started with the XML first. Open your activity.xml layout.

Here’s the layout skeleton.

<androidx.coordinatorlayout.widget.CoordinatorLayout >
    <com.google.android.material.appbar.AppBarLayout >
        <com.google.android.material.appbar.CollapsingToolbarLayout >
            <androidx.appcompat.widget.Toolbar />
        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>
    <include layout="@layout/content_scrolling" />
    <com.google.android.material.floatingactionbutton.FloatingActionButton />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Design Support UI Widgets

I understand if all these layouts might appear new to you. But you won’t have to worry. I’ll do my best to explain to them, in the easiest way.

1. CoordinatorLayout

A powerful FrameLayout that specifies behavior for child views for various interactions. It also allows anchoring of floating views in your layout.

2. AppBarLayout

It is a special kind of vertical LinearLayout. It helps respond to its children’s scroll events (scroll gestures). Additionally, it’s responsible for implementing many features of Material Design’s AppBarLayout.

But, there’s one thing to note. Its usage relies on being a direct child within CoordinatorLayout. The layout skeleton above demonstrates this.

Plan the Image Header Before Wiring Scroll Behavior

Choose a predictable image crop

Treat the header image as a background area, not as content that must remain fully visible at every screen size. A wide photograph can be cropped on a narrow phone, and a tall image can lose important details on a tablet. Pick an image whose subject can tolerate cropping, then preview it at the expanded header height and at several widths. If the subject needs to stay in view, place it in an ImageView and use an intentional scale type rather than relying on an arbitrary background stretch.

Steps for building and testing an Android collapsing toolbar image header
Build a Collapsing Image Header

Keep the toolbar controls legible

Text and navigation icons sit over changing image colors while the app bar is expanded, then over a solid surface after it collapses. Check the contrast in both states instead of judging only the initial screen. A content scrim provides a solid foreground as the bar moves into its collapsed state; a status bar scrim can help the status area remain readable. Select colors and title styles that match the rest of the app, and test with bright and dark portions of the chosen image.

Place the image as a collapsing child view

For more control than a fixed background provides, add an image view inside the collapsing container and place the toolbar above it in the view hierarchy. Give the image a deliberate scale type so the subject crops predictably, and set its collapse mode to parallax when you want it to move more slowly than the toolbar. Keep the toolbar in pin mode when navigation and actions should remain available after the image has scrolled away.

Use the container’s title for the screen name and connect the toolbar through its ID so the expanded and collapsed title states stay coordinated. Set a content scrim to a surface color that keeps the collapsed title readable; use a status bar scrim only when it fits the app’s window-inset and system-bar design. Avoid placing essential labels only over the image, since the image itself disappears as the user scrolls.

Check the result in both expanded and collapsed states, then test a long title, a short title, and an image with bright and dark regions. This catches crop and contrast problems early, before you add extra animation or offset-listener logic.

Phone displaying a photo header in a mobile app
Review the image header at the top of a mobile screen. · Photo / Openverse (CC0)

Separate decoration from essential information

A header image should support the screen rather than carry information that users cannot access elsewhere. If the image is meaningful, provide a suitable description through the appropriate image view accessibility properties. If it is decorative, avoid adding redundant spoken content. Keep the screen title as real text managed by the collapsing toolbar rather than baking it into the image, so it can resize, remain accessible, and appear correctly after the header collapses.

Connect the Scrolling Content Correctly

Use a scrolling sibling that cooperates with the app bar

The app bar needs a vertically scrolling sibling with the expected scrolling behavior. The existing layout uses an included content layout, so check that the included view is actually scrollable and declares the app-bar scrolling behavior. A plain container that never reports scroll movement cannot drive the collapse animation. For a long page, use a suitable nested scrolling view or a RecyclerView, and avoid wrapping one scrolling view inside another unless the design truly requires it.

Check the complete view hierarchy

CoordinatorLayout should coordinate the app bar and the scrolling content as siblings. AppBarLayout belongs directly inside that coordinator, and CollapsingToolbarLayout belongs directly inside the app bar. Extra wrappers can prevent the behavior from being discovered or applied. When an include file obscures the hierarchy, inspect the expanded layout or temporarily replace the include with a minimal scrolling view to isolate whether the problem is in the app-bar structure or in the content layout.

Choose scroll flags to match the intended motion

Scroll flags decide which app-bar children move and what remains visible after a gesture. The sample uses scroll with exit-until-collapsed, so the header can move away while the toolbar remains at its collapsed height. A pinned toolbar is a common choice for keeping navigation available, while a parallax image can move at a different rate if its layout parameters request that effect. Apply flags to the child whose movement you intend to control and verify the result with short and long content.

Debug the Collapsing Toolbar in Small Steps

When the header does not move

First confirm that the content view can scroll and that its scrolling behavior is present. Then confirm that AppBarLayout is a direct child of CoordinatorLayout and that the relevant app-bar child has scroll flags. Make sure the content is tall enough to scroll; a screen that fits entirely in the available height has no scroll gesture to trigger a collapse. Temporarily remove unrelated nested containers and behaviors until the smallest working structure responds correctly.

When the image or title disappears unexpectedly

Review the height of the app bar and the collapsing container, the toolbar’s collapse mode, and the title margins. A toolbar that is not pinned may leave the screen along with the image, while an oversized title can overlap other controls in the expanded state. Check the collapsed state separately and provide enough space for the navigation icon and any actions. Also ensure that views added inside the toolbar do not compete with the collapsing layout’s own title placement.

When the scrim or status bar looks wrong

Scrim behavior depends on how much of the app bar remains visible and on the chosen foreground colors. Try a temporary high-contrast scrim to determine whether the issue is the trigger point or simply a color that blends into the image. Verify edge-to-edge and window inset handling on the Android versions your app supports; system bars can affect the portion of the image that appears behind the toolbar. Test after rotation as well, because a different available height can change when the scrim becomes visible.

Test the Layout for Real Use

Cover screen sizes and interaction states

Test a narrow phone, a wider device, and a tablet-sized layout where the app supports one. Exercise slow drags, quick flings, upward and downward scrolling, and rotation. Confirm the title remains understandable, the toolbar actions stay reachable, and the content does not jump when the app bar changes state. Repeat the checks with an image that has both light and dark areas; a single preview image can hide contrast problems.

Mind dependencies and sample code age

The dependency versions in older tutorials are examples from their original context, not a recommendation to add those exact versions to a new project. Use the AndroidX and Material Components versions already selected for your app, and check their compatibility with the project's build setup before changing dependencies. If a copied sample references an outdated package or deprecated API, adapt it to the version in use rather than mixing older support-library artifacts with AndroidX components.

Use offset callbacks only for a clear need

An app-bar offset listener can help coordinate a secondary visual change, such as toggling a toolbar detail when the header reaches a threshold. Keep that logic tied to the actual offset and avoid updating the whole screen on every small movement. Remove the listener when its owner is no longer active, and make sure any state change remains correct after recreation or rotation. For basic image collapse and title transition, the layout behavior itself is usually enough.

3. CollapsingToolbarLayout

It is a Toolbar wrapper which makes the ‘Flexible Space’ pattern possible. It collapses the image header while decreasing the expanded title to a Toolbar title.

4. FloatingActionButton

I’m sure you’re familiar with what a Floating Action Button is, aren’t you? Android gave it a thumbs up by giving us an official UI widget. It’s a part of the Design Support Library.

Project XML Layout

Alright, with that out of the way lets get to the actual XML. This is not a complex code. XML just tends to be a little verbose. But you’re welcome to try replicating the Flexible Space scroll animation in Java. Then I’m sure you’d truly appreciate how easy the Design Support library is.

activity_scrolling.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".ScrollingActivity">
    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/app_bar_height"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">
        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            android:background="@drawable/legend_blogs"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:toolbarId="@+id/toolbar">
            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />
        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>
    <include layout="@layout/content_scrolling" />
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end"
        app:srcCompat="@android:drawable/ic_dialog_email" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

content_scrolling.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".ScrollingActivity"
    tools:showIn="@layout/activity_scrolling">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/text_margin"
        android:text="@string/large_text" />
</androidx.core.widget.NestedScrollView>

ScrollingActivity.java

package com.codingissue.legendblogsexample;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class ScrollingActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrolling);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_scrolling, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Conclusion

In Android, the Design Support Library makes it easy to create powerful animations, like this one. It allows us to create rich app experiences our users can enjoy. In the above code, to know whether the CollapsingToolbarLayout is collapsed or expanded. we add a listener addOnOffsetChangedListener on the AppBarLayout instance. Depending upon the if-else conditions we show or hide the toolbar info option.

Related posts

Write a comment