Android CollapsingToolbarLayout - Material Design Tutorial -2

Android CollapsingToolbarLayout:

In this tutorial, we will learn to create a collapsing toolbar layout that was introduced with Design Support library . Before starting anything, let’s check for the new layouts that were introduced with design library :

CoordinatorLayout :

This is a super powered FrameLayout. We can specify behaviours for child views of coordinatorlayout for various interections.

Appbar Layout: 

AppBarLayout should be used as a direct child of coordinatorLayout. Basically, it is a vertical Linear Layout , children of which can manage the behaviour when the content is scrolled. setScrollFlags(int) or app:layout_scrollFlags is used to provide their children their desired scrolling behavior.

CollapsingToolbarLayout :

This layout is a wrapper for toolbar which implements a collapsing app bar . It is used as a direct child of AppBarLayout.

collapsingtoolbar

CollapsingToolbarLayout has the following features :

Collapsing title :

A Title that is larger when the layout is fully visible and becomes smaller when the layout is scrolled off the screen. setTitle(CharSequence)can be used to set the title .collapsedTextAppearance and expandedTextAppearance attributes are used to change the title appearance.

Content scrim :

A full-bleed scrim that will be shown or hidden when the scroll position has hit a certain threshold.We can change it using setContentScrim(Drawable).

Status bar scrim:

A scrim that will be shown or hidden behind the status bar when the scroll position hits a threshold value. setStatusBarScrim(Drawable) can be used to change this. This will work only on lollipop devices.

Sample Application :

  1. Create a project on Android Studio with an Activity “ScrollingActivity” and its corresponding layout “activity_scrolling.xml” .
public class ScrollingActivity extends AppCompatActivity {

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

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

        //get the bitmap of the drawable image we are using as background
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.amsterdam);


        //using palette, change the color of collapsing toolbar layout
        Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
            public void onGenerated(Palette palette) {
                int mutedColor = palette.getMutedColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
                int mutedDarkColor = palette.getDarkMutedColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimaryDark));
                int vibrantColor = palette.getVibrantColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent));

                collapsingToolbarLayout.setContentScrimColor(mutedColor);
                collapsingToolbarLayout.setStatusBarScrimColor(mutedDarkColor);
                fab.setBackgroundTintList(ColorStateList.valueOf(vibrantColor));

            }
        });


    }

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

activity_scrolling.xml

<?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.sampletest.democollapsingtoolbar.ScrollingActivity">
<!--image used is downloaded from : https://pixabay.com/en/amsterdam-night-canals-evening-1150319/-->
    <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:background="@drawable/amsterdam"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <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"
        android:src="@android:drawable/ic_dialog_email"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end" />

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

content_scrolling.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.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="com.sampletest.democollapsingtoolbar.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" />

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

You can see in the activity_scrolling.xml file that CoordinatorLayout is the base layout and AppbarLayout is working as parent layout of CollapsingToolbarLayout.

Also we are using the palette library to change the Content Scrim and StatusBar Scrim color of the collapsing toolbar layout in the ScrollingActivity :

collapsingToolbarLayout.setContentScrimColor(mutedColor);

collapsingToolbarLayout.setStatusBarScrimColor(mutedDarkColor);

That’s it. Cone this project from github hereand try to run it . If you have any query or if you are having any problem running this project, please comment below.