Android Collapsing ToolbarLayout Example

By | November 7, 2015

With the new Design support library for Android, it has become easier for us to create some great animations with minimal effort , CollapsingToolbarLayout is the newly introduced in Lollipop , using which you can create awesome scrolling effects .According to the android documentation  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

Build Gradle

Add the following lines to the dependencies section in your project’s build.grade file and sync .
It include design support library , cardview library and palette library .

file : build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:design:23.0.1'
    compile 'com.android.support:cardview-v7:23.0.1'
    compile 'com.android.support:palette-v7:22.2.0'
    }

XML Layout

Create  XML layout file in res/layout and name it activity_main.xml

file : activity_main.xml

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

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

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

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/profile_pic"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin" />

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

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

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffe5e5e5″
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingTop="10dp">

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

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

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

    </LinearLayout>

   </android.support.v4.widget.NestedScrollView>

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

Create a XML Layout inside res/layout by filename card_layout.xml and add cardview to it .
In the previous tutorial we have seen how to create android cardview.

file : card_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="12dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Lorem ipsum"
            android:textSize="20sp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/text_content"
            android:textSize="18sp" />

    </LinearLayout>

</android.support.v7.widget.CardView>

Lets Understand the XML Tags in the above xml layout

1. CoordinatorLayout

A powerful FrameLayout that specifies behavior for child views for various interactions. Allows floating views to be anchored in layout.

2. AppBarLayout 

Is essentially a LinearLayout (vertical). It helps respond to its children’s scroll events (scroll gestures). Responsible for implementing many features of material design’s app bar. Depends heavily on being used as a direct child within CoordinatorLayout.

3. CollapsingToolbarLayout 
Wrapper for Toolbar that makes the header image collapse into the Toolbar adjusting its title size.
What’s left is the ImageView which holds our actual header’s image and Toolbar which we’re familiar with.

4. NestedScrollView

It’s an special scroll view for the smooth scrolling effect, inside this place the desired content . Here in this example will add several Cards as its children.

Straight from the developer’s blog:

Flags include :

  1. scroll: this flag should be set for all views that want to scroll off the screen – for views that do not use this flag, they’ll remain pinned to the top of the screen.
  2. enterAlways: this flag ensures that any downward scroll will cause this view to become visible, enabling the ‘quick return’ pattern .
  3. enterAlwaysCollapsed: When your view has declared a minHeight and you use this flag, your View will only enter at its minimum height (i.e., ‘collapsed’), only re-expanding to its full height when the scrolling view has reached it’s top.
  4. exitUntilCollapsed: this flag causes the view to scroll off until it is ‘collapsed’ (its minHeight) before exiting .

Note : all views using the scroll flag must be declared before views that do not use the flag.This ensures that all views exit from the top, leaving the fixed elements behind.

For CollapsingToolbarLayout XML Tag set the layout_scrollFlags property with
scroll|exitUntilCollapsed 

Collapse Mode

  • Parallax scrolling with the ImageView is achieved by simply setting its layout_collapseMode to parallax.
  • The Toolbar must use pin as its collapseMode because we want the Toolbar to persist and remain on top as the user scrolls down.

The Above XML Layout Inflate the view as below.

 

MainActivity

Now Inside the Activity we will see how to change the TextAppearance and Coloring of Toolbar Dynamically when Collapsing Toolbar  expands and collapse .

Get the reference of the collapsingtoolbarlayout .

 private CollapsingToolbarLayout collapsingToolbarLayout
 collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);

1. Dynamic TextAppearance :

Setting The Title Large when the layout is expanded(layout is fully visible) and Smaller when the layout is collapsed(layout is scrolled off screen)

Add the following style code inside the style.xml .

   <style name="expandedappbar" parent="@android:style/TextAppearance.Medium">
        <item name="android:textSize">48sp
        </item>
        <item name="android:textColor">@color/white</item>
        <item name="android:textStyle">bold</item>
    </style>

    <style name="collapsedappbar" parent="@android:style/TextAppearance.Medium">
        <item name="android:textSize">18sp</item>
        <item name="android:textColor">@color/white</item>
    </style>
 collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.collapsedappbar);
 collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.expandedappbar);

2. Dynamic Toolbar Coloring :  

We’ll pass our image view’s bitmap to the Palette API, which will generate colors based on the image in an PaletteAsyncListener. Upon completion, we can fetch the color we want and set it to our CollapsingToolbarLayout,  which in turn will color our Toolbar when we scroll up.

 Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.profile_pic);
        Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
            @Override
            public void onGenerated(Palette palette) {
                collapsingToolbarLayout.setContentScrimColor(palette.getMutedColor(R.attr.colorPrimary));
                collapsingToolbarLayout.setStatusBarScrimColor(palette.getMutedColor(R.attr.colorPrimaryDark);
            }
        });

The Complete MainActivity Source code

file : MainActivity.java

package com.tutorialsbuzz.collapsingtoolbardemo;

import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

    private CollapsingToolbarLayout collapsingToolbarLayout = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        collapsingToolbarLayout.setTitle(getResources().getString(R.string.user_name));

        dynamicToolbarColor();
        toolbarTextAppernce();
    }

    private void dynamicToolbarColor() {

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.profile_pic);
        Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {

            @Override
            public void onGenerated(Palette palette) {
                collapsingToolbarLayout.setContentScrimColor(palette.getMutedColor(R.attr.colorPrimary));
                collapsingToolbarLayout.setStatusBarScrimColor(palette.getMutedColor(R.attr.colorPrimaryDark);
            }
        });
    }

    private void toolbarTextAppernce() {
        collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.collapsedappbar);
        collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.expandedappbar);
    }

}

Scrolling Effect with Dynamic TextAppearance and Toolbar Coloring According to Image