Tutorial

Android CollapsingToolbarLayout Example

Published on August 3, 2022
Default avatar

By Anupam Chugh

Android CollapsingToolbarLayout Example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Welcome to Android CollapsingToolbarLayout Example. In this tutorial, we’ll discuss and implement CollapsingToolBarLayout in our application.

Android CollapsingToolbarLayout

Android CollapsingToolbarLayout is a wrapper for Toolbar which implements a collapsing app bar. It is designed to be used as a direct child of a AppBarLayout. This type of layout is commonly seen in the Profile Screen of the Whatsapp Application. 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 such as “100”.

If you’ve updated to the latest SDK recently choose the Scrolling Activity type (it contains a ready-made implementation of CollapsingToolbarLayout) while creating a new project. android CollapsingToolbarLayout example Running the default new project should show an output like this: android collapsing toolbar example In this tutorial, we’ll be doing changes in the default project such as showing an ImageView, showing the toolbar equivalent icon from the FAB button, when it’s collapsed.

Android CollapsingToolbarLayout Example Project Structure

android
CollapsingToolbarLayout project

Android CollapsingToolbarLayout Code

The activity_scrolling.xml is given below:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.journaldev.collapsingtoolbarlayout.ScrollingActivity">

    <android.support.design.widget.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">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">


            <ImageView
                android:id="@+id/expandedImage"
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:scaleType="centerCrop"
                android:src="@drawable/photo"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.7" />

            <android.support.v7.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" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_scrolling" />

    <android.support.design.widget.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_info" />

</android.support.design.widget.CoordinatorLayout>

app:layout_anchor and app:layout_anchorGravity anchors the FAB to the bottom right of the AppBarLayout Note: content_scrolling.xml stays as the default for this tutorial. The menu_scrolling.xml file is defined as given below

<menu xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    tools:context="com.journaldev.collapsingtoolbarlayout.ScrollingActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_info"
        android:orderInCategory="200"
        android:title="info"
        app:showAsAction="ifRoom"
        android:icon="@android:drawable/ic_dialog_info"/>

</menu>

The code for ScrollingActivity.java is defined below:

package com.journaldev.collapsingtoolbarlayout;

import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class ScrollingActivity extends AppCompatActivity {


    private Menu menu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrolling);
        final Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);

        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();
            }
        });

        AppBarLayout mAppBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            boolean isShow = false;
            int scrollRange = -1;

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (scrollRange == -1) {
                    scrollRange = appBarLayout.getTotalScrollRange();
                }
                if (scrollRange + verticalOffset == 0) {
                    isShow = true;
                    showOption(R.id.action_info);
                } else if (isShow) {
                    isShow = false;
                    hideOption(R.id.action_info);
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        this.menu = menu;
        getMenuInflater().inflate(R.menu.menu_scrolling, menu);
        hideOption(R.id.action_info);
        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;
        } else if (id == R.id.action_info) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void hideOption(int id) {
        MenuItem item = menu.findItem(id);
        item.setVisible(false);
    }

    private void showOption(int id) {
        MenuItem item = menu.findItem(id);
        item.setVisible(true);
    }
}

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. The output of the application in action is given below android CollapsingToolbarLayout example app This brings an end to this tutorial. You can download the Android CollapsingToolbarLayout Project from the link given below.

Download Android CollapsingToolbarLayout Example Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Anupam Chugh

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
January 16, 2021

At the moment when you call the last two methods, it gives an error saying that menu is a null object. And when I look back at your code I noticed that you are not initializing menu in onCreate method but in onCreateOptions method. I thought that onCreate will be called before onCreateOptions.

- emmanuel agyapong

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 24, 2020

    Many thanks for this tutorial ! ? Thanks to @Bangonkali too for the fork

    - Matdev

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      December 14, 2019

      How to change the title manually using JAVA file ?

      - Xaif

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        November 20, 2019

        Sharing this fork of this project with AndroidX support. https://github.com/bangonkali/CollapsingToolbarLayout

        - Bangonkali

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          March 5, 2019

          Hello thank for all Please I want create book app , how can I do ?

          - Guillaume Lewis

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            October 28, 2018

            hi anupam, thanks for great tutorial. I appreciate your efforts to create this tutorial. I have a question. what if title of toolbar is long… is there any way we can wrap the text in this toolbar?

            - Muddassir

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              June 13, 2018

              Thank you. This helped me out !

              - Elyes

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                April 19, 2018

                Very nicely done. Thank you for spending the time and effort in sharing this :) Saved me hours of troubleshooting and learnt along the way.

                - Julian Mummery

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  July 19, 2017

                  Thank you so much

                  - ASHUTOSH DUBEY

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    May 21, 2017

                    best post

                    - فروشگاه خرید اینترنتی

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more
                      DigitalOcean Cloud Control Panel