Android CollapsingToolbarLayout Example

Filed Under: Android

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="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="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="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://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.

Comments

  1. Guillaume Lewis says:

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

  2. Muddassir says:

    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?

    1. Anupam says:

      Use Auto sizing TextView.

  3. Elyes says:

    Thank you. This helped me out !

  4. Julian Mummery says:

    Very nicely done. Thank you for spending the time and effort in sharing this 🙂

    Saved me hours of troubleshooting and learnt along the way.

    1. Anupam says:

      Glad that it was helpful to you Ashutosh. If you want me to cover any topics feel free to comment below!

  5. فروشگاه خرید اینترنتی says:

    best post

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages