Toolbar Animation with Android Design Support Library

With the new Design support library for Android, it has become easier for us to create some great animations with minimal effort. Let’s look at how to create an app with a collapsing Toolbar animation.

In this post I’ll show you how to create a popular design pattern for a Toolbar called ‘Flexible Space with Image‘, as pointed out by Ian Lake.

Flexible Space with Image Pattern

The ‘Flexible Space with Image‘ is a scrolling technique, convenient when displaying images as a large header, with a subsequent list below it, say a contact’s detail page.

This is a pattern is part of Material Design. In familiar terms, you can see this in WhatsApp’s new updated design, View contact screen.

toolbar animation android design support library

 

Notice the Toolbar dynamically changes color, depending on the image. It takes on the most dominant color present in the image.

We will do this with the Palette API. More on that later.

Nothing scary in terms of code logic. A majority of that is XML only. Cheers to that!

NOTE:
Make sure you’ve updated ALL relevant support libraries to the latest version (22.2.0 at the time of writing this post). This avoids unusual app behaviors you might experience with the older versions.

Other Design Support Library tutorials:

As always, we’ll get started with the XML first.

Layout Structure

Open your activity.xml layout. The hierarchy will be like this:

<android.support.design.widget.CoordinatorLayout >

    <android.support.design.widget.AppBarLayout >

        <android.support.design.widget.CollapsingToolbarLayout >

            <ImageView />

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

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

    <!-- Your scrollable content here -->
</android.support.design.widget.CoordinatorLayout>

I know all these layouts are new. I will do my best to explain them all in the most concise manner.

CoordinatorLayout

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

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.

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.

Defining the layout

Layout might look threatening in size! You have been warned.

<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:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="192dp"
        android:fitsSystemWindows="true"
        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"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginBottom="32dp"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/header"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/header"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/anim_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

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

    <android.support.v7.widget.RecyclerView
        android:id="@+id/scrollableview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        android:clickable="true"
        android:src="@drawable/ic_action_add"
        app:layout_anchor="@+id/appbar"
        app:layout_anchorGravity="bottom|right|end" />
    
</android.support.design.widget.CoordinatorLayout>

Hey, if you think this is complex, you’re welcome to look at the amount of code it took to achieve an Toolbar animation before this library!

However, I have highlighted the essential lines needed to make the Toolbar animation work.

What you need to know from this?

You must set the layout_scrollFlags for the CollapsingToolbarLayout.

Here’s what the flags mean, straight from the developer’s blog:

  • 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
  • exitUntilCollapsed: this flag causes the view to scroll off until it is ‘collapsed’ (its minHeight) before exiting

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.

Note I haven’t set any color for the Toolbar. That will be taken care of by the CollapsingToolbarLayout. It will dynamically pick a color from our image, and set it to the Toolbar on scroll.

Floating Action Button

I’ve taken this chance to quickly show you how easily a Floating Action Button (FAB) can now be implemented thanks to the library (Yes, my previous 4 posts on FAB, are now redundant).

You will notice I’ve not explicitly defined a set size for the FAB. It will take the default size automatically, unless you want to specify the mini size, then use app:fabSize="mini". The anchor for the FAB is the AppBar and the gravity set, positions the FAB as seen previously on the output (i.e. the AppBar’s bottom right).

That’s a wrap for the XML part. The good news is, with this XML setup, the entire Toolbar animation will be handled by it. Now we just need to do the usual Toolbar initialization in Java and call in the Palette API to fetch our color.


Dynamic Toolbar coloring

Open your Activity.java and start off with the usual initialization.

toolbar = (Toolbar) findViewById(R.id.anim_toolbar);
setSupportActionBar(toolbar);

collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbar.setTitle("Suleiman Ali Shakir");

ImageView header = (ImageView) findViewById(R.id.header);

Earlier I mentioned the CollapsingToolbarLayout will be responsible for setting your Toolbar‘s color dynamically.

The title for the CollapsingToolbarLayout ideally, is your Toolbar title. Here I’ve simply chosen to set my name, for the lack of a better title.

Palette API

We’ll pass our header view’s bitmap to the Palette API, which will generate colors based on the image in an AsyncTask.

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 down.

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.header);

        Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
            @Override
            public void onGenerated(Palette palette) {

                mutedColor = palette.getMutedColor(R.attr.colorPrimary);
                collapsingToolbar.setContentScrimColor(mutedColor);
            }
        });

I am fetching my bitmap from my resources directory.

However in a real world scenario, you would mostly be downloading the image from a URL. Then saving it as a bitmap and passing that to the Palette API.

The Palette API offers several color options (variations):

  • Light
  • Dark
  • Vibrant
  • Muted

You can also increase the amount of colors generated from the image or even retrieve the entire color swatch. If you’re interested in playing around with the Palette API, I’d suggest you go through Chris Banes’ post .


Toolbar Animation in Action

With that, its complete! Go ahead and run your app and watch the magic.

Honestly, I was surprised the first time at just how smooth the Toolbar animation is. Even the FAB reacts beautifully upon touch with a higher elevation.

Check out the code sample over at my Git.


The new Design Support Library makes it possible to create such powerful animations with ease. This allows us to create rich app experiences our users can enjoy.

Material Design is a powerful visual language that can help you design a brilliant app.

But being relatively new, do note that the library is bound to have bugs. For instance, the FAB doesn’t display a shadow, and other irregularities on Lollipop. Hopefully all these would be resolved in the next update.

If you’re interested in Material Design for Android, there is an online class by Google on Udacity. I highly recommend you check it out. One would benefit greatly.

ISSUESSome of you make experience some Toolbar padding issues on Lollipop. It’s documented here.

Do subscribe and stay updated as I will be posting more stuff like this as I continue to tinker and see what more is possible with the Design Support Library!

Suleiman

Android developer and tech enthusiast. Love creating apps with good UI UX design. I also like to sketch and listen to Chillstep.

You may also like...

  • panas

    is there any way for the title to stay on toolbar and not get expanded? or to add a textview to the collapsingtollbarlayout and when get collapsed to pin under the toolbar?

    • Could you please specify what you’re saying? Do you mean like an additional view below the Toolbar, which sticks on top of the screen when you scroll?
      Something like this?
      http://4.bp.blogspot.com/-9jn0pCtadO8/U9_E1mlg8CI/AAAAAAAAAt4/yr9CCSThkpg/s640/change_1.gif

      • panas

        yes this

        • If you note the animation originally in my post, The CollapsingToolbarLayout has:

          1. Expanded title (before scrolling, large text)
          2. Collapsed title (after scrolling, Toolbar title)

          Set both of those to a consistent text appearance. Set app:collapsedTitleTextAppearance and app:expandedTitleTextAppearance to “@style/TextAppearance.AppCompat.Title”

          • panas

            i dint make that work :(. the text goes up to the toolbar and not bpined below it

          • In that case, I suggest you check this out.

            https://plus.google.com/+RomanNurik/posts/1Sb549FvpJt

            What you’re asking for is a “StickyView”, do check the video first and then the code sample which is linked above.

          • Naresh Jain

            Hi panas
            Did you get answer this if yes please share the code…

          • Jitesh H Lalwani

            Just add

            app:layout_scrollFlags=”scroll|exitUntilCollapsed”

          • Avtar Singh

            @suleiman19:disqus Hey, Could you please share the code of the “First” one above…I tried a lot, but its not working as shown in above gif…the left one…..”First Release”

          • Hey there,
            If you followed this post, there’s only slight modifications to be done to get that effect.

            Set an expanded Toolbar height. (Toolbar, not AppBar).
            Then inside the AppBar tags, add regular TextViews.

            The key to getting this work is to NOT have a title for Toolbar and CollapsingToolbar. But instead use a regular TextView inside your AppBarLayout.

            Let me know if that helped you.

          • Avtar Singh

            okie, thanks for replying…..let me try again, and will inform you in an hour or two, thanks

          • Avtar Singh

            Thanks @suleiman19:disqus for replying, will try again, and inform you in an hour or two, thanks

          • Avtar Singh

            Suleiman19 hey,

            I tried it, and I got 50% success, there are some issues, or may be I am not understanding the concept clearly.

            I set the Height of “Toolbar” to 100dp, just for testing, for the time being.

            1. Inside my AppBarLayout first one is “CollapsingToolbarLayout” and then second one is “Textview”. But the Textview is hidden, means behind RecyclerView, I think so…How to make it visible

            2. I havent set any title for “Toolbar” and “CollapsingToolbarLayout”, but still its showing the Activity name over there. How to remove that.

            These 2 issues I am getting. Please Help

            Actually what I reaaly want is a “RelativeLayout” or any other Layout containg 2 textviews, that should be shown only when the Toolbar is Collapsed and the Layout should be below the Toolbar as in the above gif pic…..but the layout should go down and become transparent with the expanding toolbar as shown in above gif pic

          • Your RecyclerView needs to use app:layout_behavior attribute.
            What about your ImageView? TextView needs to be above that. Apart from all that, the layout remains the same from this post.

            If the RecyclerView still gives issues, try placing it above the AppBarLayout START tag, rather than the END. (helps me at times).

            To not display a title, use these:
            getSupportActionBar().setDisplayShowTitleEnabled(false);

            collapsingToolbarLayout.setTitleEnabled(false);

          • Nidhin Vasudev

            how can i add subtitle for the collapsingToolbarLayout

          • You’ll have to include a TextView inside your Toolbar. This should help: http://stackoverflow.com/questions/31194280/collapsingtoolbarlayout-subtitle

      • panas

        can you share the code or make a new post please?

      • Virat Nirmal

        can anybody post xml code of “First Release” ? please.

      • Dhaval P

        can you please share the xml code for the first release?

        • Hi Dhaval,
          Entire sample project is available on GitHub. Check the end of the post for a link.

  • I saw “app:layout_behavior=”@string/appbar_scrolling_view_behavior””, but what is it?

    And where could I find your original project about this sample?

  • Witalo Benicio

    Im not able to get this working. I did EXACTLY the same…and only what scrolls its the Recycler

    • Witalo Benicio

      If i get your project from github and run in my nexus 5 i get the effect, but i do the exact same code and isnt work :/

      • Hi Witalo,

        If you’re having scroll issues, I suggest you change your layout like this and give it a try. Instead of adding the RecyclerView AFTER the AppBarLayout close tag, add it immediately after you OPEN the AppBarLayout tag.

        • Witalo Benicio

          Hi Suleiman i have created another project to test if it works, and WORKED.
          I think it may be a problem with some lib that im using.
          This are my dependencies:
          dependencies {
          compile fileTree(dir: ‘libs’, include: [‘*.jar’])
          apt “org.androidannotations:androidannotations:${AAVersion}”
          compile ‘com.android.support:appcompat-v7:22.2.0’
          compile ‘com.android.support:support-v4:22.2.0’
          compile ‘com.android.support:cardview-v7:22.2.0’
          compile ‘com.google.android.gms:play-services:7.0.0’
          compile ‘com.facebook.android:facebook-android-sdk:3.23.0’
          compile ‘com.android.support:design:22.2.0’
          compile ‘com.android.support:palette-v7:22.2.0’

          compile “org.androidannotations:androidannotations-api:${AAVersion}”
          compile ‘com.github.ksoichiro:android-observablescrollview:1.5.0’
          compile ‘de.hdodenhof:circleimageview:1.2.1’
          compile ‘com.pnikosis:materialish-progress:1.5’

          compile ‘com.googlecode.android-query:android-query:0.25.9’
          compile ‘com.squareup.okhttp:okhttp:2.3.0’
          compile ‘com.squareup.okhttp:okhttp-urlconnection:2.0.0’
          compile ‘com.google.code.gson:gson:2.3.1’
          compile ‘com.orhanobut:wasp:1.9’

          compile ‘com.nineoldandroids:library:2.4.0’
          compile ‘com.daimajia.easing:library:1.0.1@aar’
          compile ‘com.daimajia.androidanimations:library:1.1.3@aar’
          compile ‘com.melnykov:floatingactionbutton:1.2.0’
          compile ‘com.afollestad:material-dialogs:0.6.4.7’
          compile ‘com.orhanobut:simplelistview:1.2@aar’
          compile ‘com.squareup.picasso:picasso:2.5.2’
          }

          —-

          Edit: Nope, its not a problem with my dependencies, since i passed all of them to the new project and it worked pretty well.
          Im trying to use the design support in a current app and does not work, but in a new project, works.

          • Whoa! Those are a LOT of dependencies Witalo! :O
            Since you’re including the Design library, keep the AppCompat library. Remove the Support-v4, you don’t need it since the Design library depends on that as well. 🙂

            Do bear with it as the Design support library is very ambitious yet relatively new. Many issues have been identified and reported. It should be fixed in the next update.

            Cheers!

          • Witalo Benicio

            I put all those libraries in the new project that I mentioned that was working and the project still work with the parallax effect. Only my older project doesn’t work

          • You could try it on a barebones project by adding those dependencies with the design library one by one and check which gives you the issue.
            Also if you mentioned if the issues comes on a Lollipop or pre Lolipop device, it would be helpful.

          • Witalo Benicio

            I did that. On the new project it works…even with all libraries.

          • Frosty

            That’s great Witalo. Awesome! 🙂

          • That’s great Witalo. Awesome!

          • Witalo Benicio

            But what do you think what is the problem with the older problem since that are not the libraries?

          • It’s hard to tell without looking at your code. Link to GitHub or something?

    • Pri

      Make sure you’re using com.android.support:recyclerview-v7:22.2.0 , same problem with me, I updated the version and it works

      • Thanks for pointing that out. I assumed everyone would have updated their respective libraries to the latest.

  • Paritosh Tonk

    Is there a way such that the I get a square AppBarLayout?

    • Hi Paritosh,
      What do you mean by a ‘square’ AppBarLayout? Could you please specify?

      • Paritosh Tonk

        I got it that way by overriding onMeasure of AppBar Layout. “Square” meaning that height =width so as to have a square album art.

        • Great Paritosh. Glad to know you got it to work! 🙂

  • Robert

    Hey is there way that the collapsed toolbar does not stay pinned at the top but scrolls out with the content in a collapsing toolbar layout and vice versa? I have tried to remove the layout_collapseMode=”pin” from the toolbar but it didnt give me the desired behaviour.

    • Add ‘enterAlways’ to the scrollFlags in your CollapsingToolbarLayout. This enables the ‘Quick Return’ pattern which you’re asking for.

      However do note that sometimes, on scrolling up, a blank space appears on top instead of the Toolbar. Might be an issue with the Design library itself. Do give it a try though!

  • Pri

    app:layout_collapseMode=”pin” not working for Toolbar

    Toolbar getting scrolled with recyclerView

    • It’s hard to tell without looking at your layout. Can you cross check your layout against mine to make sure it matches?

    • I have tested and can confirm that it works. Check the scroll flags on the AppBarLayout.
      Do update all respective support libraries to their latest versions (22.2.0). This can help avoid any unintended app behavior.

      • Prathmesh Deshmukh

        I downloaded your project from git and changed nothing. But still toolbar was getting scrolled along with recyclerView as Pri said.

        Edit: Got it working by changing app:layout_scrollFlags=”scroll|enterAlwaysCollapsed” to
        app:layout_scrollFlags=”scroll|exitUntilCollapsed”
        in collapsingToolbarLayout

  • Pri

    android.R.id.home not appearing on toolbar in AnimateToolbar Activity. Please help.

    • android.R.id.home is used in onOptionsItemSelected to go back to the previous Activity with the ‘finish()’ method. Why is that an issue? What do you mean by ‘not appearing’? Please specify.

  • Santino Wang

    where is app:layout_behavior=”@string/appbar_scrolling_view_behavior”?

  • Andrii

    Have you noticed bug with rotation and CoordinatorLayout? @suleiman19:disqus Do you have some ideas how to fix it?
    Moto G, Android 4.4.4

  • Ed Foux

    Thank you very much for the great Article!
    Do you know by the chance how to set the collapseMode (pin or parallax) programmatically?

    • Thanks Ed. I’m glad you liked it 🙂
      You can use toolbar.setCollapsible(boolean);
      Apart from that I don’t see any method exposed that lets us set the MODE. So I’m afraid you’ll have to do that via XML.

      • Ed Foux

        Thank you, Suleiman19! Trying out the xml layout approach.

  • blu

    How can I stop the toolbar from collapsing entirely if there isn’t enough content in the nestedScrollView to fill the space below?

    • That’s weird. Have you Adding any spacing below your Toolbar? The entire NEstedScrollView is supposed to sit directly below the Toolbar. If there isn’t enough content in your scroll view, there would be spacing at the bottom. Not the top.

      Can you post your layout to StackOverflow so I could have a look?

      Thanks

      • blu

        Suleiman19, If I add a layout_gravity=”fill_vertical” to the NestedScrollView it will scroll all the way to the top, but that’s not really what I want either. I’d like to have the CollapsingToolbar stop collapsing as soon as the nested scrollview runs out of content to scroll. Currently, the Contacts app on Android 5.1.1 does this. I will get my code and stackoverflow and post a link.

        • Do link to your issue at Stack Overflow so I can have a look.
          Moreover, you can consider adding an empty View in your NestedScrollView, whose height = the extra height required by the Toolbar to collapse completely. So this would make the NestedScrollView ‘appear’ to have enough content.

      • blu
  • Tshepo Stark

    Good Day, i did everything like you said but the header does not resize into a toolbar or anything. it just remains static

    • Hi there,

      Can you cross check your code against mine? Just to make sure you haven’t missed out on anything. I’ve provided a GitHub link at the post end for reference.

      • Tshepo Stark

        Wow, you reply very fast hey. I just went through all your comments and found the solution, I just has to update my recyclerview library. Thank you so much for this hey, been struggling for ages to get this effect. Do you know how I can make the toolbar pop back into the screen when I scroll up and disappear once again as I scroll down?

        • Just happened to be online 🙂

          Add ‘enterAlways’ to the scrollFlags in your CollapsingToolbarLayout. This enables the ‘Quick Return’ pattern which you’re asking for.

          • Tshepo Stark

            Thanks a lot, worked super… Thanks.man, any advice on how to change the toolbar color? I tried everything and it still remains purple

          • change your colorPrimary in styles.xml

  • Santino Wang

    is this working on 5.0.2 device?
    it is working in 4.x and 5.1 device, but not shown in 5.0.2 device………

    • I test on a 5.0.0 device, everything works fine in that. Haven’t tried in 5.0.2. Could you specify as to ‘what’ is not working?

    • Santino Wang

      I am saying the toolbar is gone. It is the known issue, which you mention it in your post. Really helpful! thank you!

  • Hi Prathya,
    Please migrate over to RecyclerView for it to work.

  • Do check my previous reply. Have you tried that?

  • Ed Foux

    Hello! I have implemented animated toolbar with the parallax effect. I am experiencing an issue when the listview when it scrolls underneath the toolbar sometimes.
    https://youtu.be/dyzhZZiRfpU
    Please follow the provided link address: You would see initially the expected behavior, where the image on top collapses in parallax effect when the list view is in the initial position. However, when the listview is not all the way on the bottom, it tends to move underneath the toolbar when it is scrolled up.

    Please share your thoughts. Thank you!

    • Are you trying to mimic an Instagram type of an effect?
      The CollapsingToolbar is intended to work only when there is a large header image followed by a list. So it must contain ONE header image, and a Toolbar.

      Have you cross-checked against my layout?

  • Giuseppe Calaprice

    Hi, is there a way to set also a subtitle in CollapsingToolbarLayout?

    • Hey there,
      Sorry to disappoint but the CollapsingToolbarLayout provisions only for a title and not for a subtitle, yet.

  • Jason Moix

    Thanks for the awesome guide! I’m having a bug I can’t seem to get rid of however. When I collapse the toolbar everything works fine, however, when I expand it everything expands too far down the screen leaving behind an empty space for a toolbar. Do you have any idea why this could be happening? I’m at my wits end… hehe. Thanks!

    • Hi Jason,
      Can you please cross check your code against mine once? I’ve provided a GitHub link to the code source as well. Seems to be a layout issue, so I’d start with the Activity’s xml files.

      • Jason Moix

        I got it! In order to get the toolbar to expand completely, I set the scroll flags for it to ‘app:layout_scrollFlags=”scroll|exitUntilCollapsed|enterAlways”. This caused a bug when it was re-expanding. In order to fix it, I removed the ‘enterAlways’ flag from the CollapsingToolbarLayout and placed it instead in the ImageView for the header. This way, only the backdrop enters always. Everything works great now. Thanks!

        • Exactly why I asked you to cross check. I didn’t include the ‘enterAlways’ flag.
          Great that you got it working Jason!

          Cheers.

  • I can’t compile ‘it.sephiroth.android.library.viewrevealanimator:view-reveal-animator:’ and give the error fail to resolve

    • That was a library I included for testing. It’s of no relation to the Toolbar Animation. You can bravely remove it 🙂

  • Pingback: Android implementing adapter for RecyclerView | JAVA()

  • Pingback: Implementing an adapter for RecyclerView in Android - BlogoSfera()

  • Mwas

    Thank you for this tutorial. It saved me alot of time.

  • BrandonWhite116

    Is there anyway to get a callback when the Toolbar is collapsed? I would like to change the theme of my toolbar once it collapses.

  • Glad you found the tutorial useful!
    About your issue, try loading your entire layout from a fragment. (Apart from the navigation drawer layout).

    Trying to make the Status Bar work in conjunction with a Collapsing header AND Navigation Drawer is indeed messy.

    For scrolling, there is a neat method you could try: scrollToPosition() https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html#scrollToPosition(int)

    Pass your adapter’s item position. So while your activity loads, it does so scrolled down a little and your image has lesser height. User can scroll up to reveal more, or scroll down to hide.

    Hope that helps you.

    • Aviad Moreshet

      1. How do I do that?
      My entire app contains a single Drawer Activity with a navigation view & toolbar.
      In the middle of the screen I have a Frame Layout which I keep switching for each fragment chosen from the nav view, as usual.

      The problem is, I had to do this flexible space view in another activity since it has a very different view from the other main layout, such as a CollapsingBar Layout, an ImageView inside the AppBar Layout, and unique attributes to the layouts,
      and also, the new fragment lacked basic methods I needed to use which only AppCompatActivity had, in order to deal with the layout switching, so I decided to simple make a new activity.
      Can you please help me with that? I think you’re the only one got a chance.

      2. scrollToPosition doesnt work. Using it like this:

      mRecyclerView = (RecyclerView) findViewById(R.id.activity_profile_bottom_recyclerview);
      mRecyclerView.setHasFixedSize(true);
      mLayoutManager = new LinearLayoutManager(this);
      mRecyclerView.setLayoutManager(mLayoutManager);
      if(mAdapter == null){
      mAdapter = new ProfileAdapter(this, user);
      mRecyclerView.setAdapter(mAdapter);
      }
      mRecyclerView.scrollToPosition(mAdapter.getItemCount() – 1);

      • While loading a new activity is straight off an easier solution, it should still work fine.
        The scrollToPosition scrolls to a specific item in the list. The position specified here is the adapter item’s count position. Is that working for you?

        • Aviad Moreshet

          Well, in the layout xml I supplied ib stackoverflow everything works fine except the status bar isn’t transparent. If it works for you (nav view with collapse toolbar), maybe its with the code?

          Regarding scrollToPosition, I’ve got 4 items in my recycler view, positions starting from 0 to 3, and scrolling to ANY position just wont work. Any more details I could give that will help to find the problem?

          • I haven’t tried that out myself yet. If you are loading the collapsible toolbar in a new activity, with the nav view being in another, I don’t see why its not working. In my sample both are separate activities and they work just fine.

            Do check my Git link for reference.

          • Aviad Moreshet

            Ok my fault!
            I realized I haven’t configued the v-21 xml properly, that’s why it didn’t work!

            Now, got the last problem: scrollToPosition not working. What can I do? Do you need code of something?

          • Scrolling was convenient when using a ListView. Its kind of a mess for RecyclerView. But your answer most likely lies in the RecyclerView’s LayoutManager. You should look into that. For instance, this link:
            http://bit.ly/1I9HQmi

  • Pingback: Android scrollToPosition | JAVA()

  • The RecyclerView can use any LayoutManager. Doesn’t matter what it is, it should work. Also, what do you mean by when you ‘try to call layout_gravity=”bottom” ‘?
    I need you to recheck your layout and activity against mine once. Can you do that?
    Also be sure to update your Design Support Library to v22.2.1

  • Pingback: Setting RecyclerView scrolling position on Android - codeengine()

  • farhan ali

    Hello Suleiman, Its a nice blog, I have an issue when trying to implement this within a Fragment. the back button and menu actions are not working, It seems like some other view over drawn above menu and back, they stay unresponsive to touch

    • Hi Farhan,
      Glad you like the blog.
      While I understand your issue, I’m afraid I won’t be able to help unless I have a look at your layout.

      • farhan ali

        I used the same layout in the blog, just replaced the RecyclerView with a ListView, thats all the change i have done. both up arrow and menu action button are showing there on top, but no actions on that !

        • You said you’re using it in a Fragment. Hope your Toolbar, CoordinatorLayout and everything else rests entirely in the Fragment itself. Maybe your Toolbar lies in the Activity and the Fragment is overlaying it.

          That could be a possible reason why its not responding to touch events.

          • farhan ali

            No, every thing is in fragment layout, I am adding that fragment to the host activity via xml layout – within a RelativeLayout using tag.

          • Won’t be able to help you much without seeing the code. Could you post on Stack Overflow so I can have a look?

      • farhan ali

        I used the same layout mentioned in blog, just replaced the RecyclerView with ListView, no other changes

  • Is there a way of changing the font? or are we stuck with the current typeface?

  • I got one serious issue on this. I scroll down, so the header is gone, and Toolbar color is solid. Then I try to scroll back starting the movement from the area the header was on. Scrolling is stuck then. I can only scroll back if I drag thea initial area of RecyclerView

    • I’ve never experienced any issues with the scroll being stuck Jacek. Could you cross check your layout against mine once? Also do update your Design Support Library to v22.2.1

  • Rowan

    I’m having trouble combining this with a RecyclerView that must occasionally do notifyItemRemoved. Specifically, removing an item (CardView in this case) that is the first item in the list while the CollapsingToolbarLayout is fully expanded. It just leaves an empty space in the RecyclerView, occasionally causing a crash but generally just leaving that empty space until I scroll up and down again. Any advice for this?

    • Hi Rowan,
      Could you please tell me more specifics like:
      on which OS version does it crash
      library versions
      a screenshot/ video would be helpful too.

  • Diego Acuña

    Hi, excellent tutorial, I’ve implemented succesfully on one of my personal projects. A quick question, do you know if you can replace the ImageView with something like a ViewPager? I’m trying to do that the imageview can be switched on a swipe from right to left. Any ideas?

    Thanks!

    • Hi Diego,
      Glad you liked the tutorial. This scroll pattern is meant to work with an image. However, as an alternative you could detect a swipe and dynamically change the ImageView.

  • Which TextView are you talking about? The one in the header view?

  • Aman Jham

    how to set the sub title in CollapsingToolbarLayout like whatsapp?

    • The group profile in WhatsApp is custom Aman. I don’t see any way to add a subtitle using the CollapsingToolbar. Sorry.

  • The Fragment usually must communicate back to the Activity’s Toolbar. It must not inflate its own. That’s the usual case.
    By using onCreateOptionsMenu() in the Fragment, its menu resources are added to the Activity’s Toolbar.
    Also make sure your Fragment layout rests BELOW the Toolbar.

    http://developer.android.com/guide/components/fragments.html

  • Eric

    Got an error— CollapsingToolbar cannot be resolved or is not a type despite using this:import android.support.design.widget.CollapsingToolbarLayout;

    • Hi Eric,
      Could you please post your entire error log?

      • Eric

        Here it’s

        • Sorry Eric, but could you post that image elsewhere? It’s too small for me to see anything!

          • Eric

            I fixed that too. Now I’m having a problem where by it does the parallax thing where the image shrinks, when I scroll down.When I try to scroll back up it works fine. Then, when I scroll down again, this time it’s able to do the parallax thing. I’m not using a list like you but rather text view.Could that be causing the problem?

          • The animation is to work for a scrollable view beneath it. i.e. a RecyclerView or NestedScrollView.

  • Baris

    Selamın Aleykum , Thank u man all it’s work . But my recycleview only work with linearlayout . it not a work alone .

    • That’s great to hear Baris. What do you mean it doesn’t work without a LinearLayout?

      • Baris

        Collapsing effect it doesnt work without linearlayout. For ex.

        Part1 xml file it’s work .

        <<CoordinatorLayout
        <<AppBarLayout
        <<CollapsingToolbarLayout
        ……. image , text stuff
        <> CollapsingToolbarLayout
        >>AppBarLayout
        >>CoordinatorLayout

        Part2 xmk file it’s not a working (collapsing effect)

        • The scroll flag is intended to be used for a scrollable view i.e. a RecyclerView or NestedScrollView.

      • Baris

        ..

  • Maybe it’s the VolleyImageView that’s causing the issue?
    I’m just speculating here but I haven’t experienced any such issues, but if I were you, I’d implement what’s exactly in the post and then modify from there. This way it should help identify the culprit.

  • Try to have either a RecyclerView OR a NesterScrollView. Not both.

  • Jitesh H Lalwani

    Same here, any solution?

  • Arth Tilva

    Hii, I am getting issue when I use RecyclerView, Toolbar isnot getting collapse, but when I use NestedScrollview with the same flags it is working fine.

    • Hey,
      If you see my example, using a RecyclerView works just fine. Do check your code against mine to see if you missed out something.

      • Arth Tilva

        I copy pasted your code… 😛

        • Have you checked with my project on GitHub? Checking your styles and Toolbar setup wouldn’t hurt as well.
          Otherwise, pls post your code so I can have a look.

          • Arth Tilva

            Thanks Suleiman I updated all the libs and it worked…

      • Arth Tilva

        Issue is that Toolbar is not getting collapsed in recyclerview scrolling.

  • Hi Danny,
    I’m unable to view the image you posted on StackOverflow. Could you post the image here for me to see?

    • Sorry about that.. I changed the image location and now it’s available in there too but I’ll upload here

    • I got it fixed eventually.. The problem was I hadn’t had a styles-v21/styles.xml file with my AppTheme extending the BaseTheme in it

      • Specifically why I insist people to cross check their code against mine multiple times. Anyway, glad you got it to work.

        • Well, the problem had nothing to do with cross checking the code.. That part was fine.. All I needed to do was create a values-v21/styles.xml file where I extended the BaseTheme

  • Pingback: android: collapsing toolbar bounces on scroll up - BlogoSfera()

  • Pingback: android: collapsing toolbar bounces on scroll up - BlogoSfera()

  • Pingback: android: collapsing toolbar bounces on scroll up - Wikiask.info()

  • Pingback: Flexible Space in Android | Solutions for enthusiast and professional programmers()

  • Pingback: Material Design ile Android Design Support Library Kullanımı | Kadın Yazılımcı()

  • Pingback: Material Design ile Android Design Support Library Kullanımı | Tuğba Üstündağ - Php Web Developer & Android Developer()

  • lythenas

    Hey, I’m having a problem with the title.
    I’m using just one activity and several fragments.
    When the AppBar is collapsed and I try to set the title the title just disappears.
    When the AppBar is fully extended it works just fine.

    Any help is appreciated.

    • And does the entire layout belong to the Activity or Fragment?
      Eitherway, the title is the same which appears when the Toolbar is expanded. (The animation is such that the expanded title collapses into the Toolbar on scroll).

  • myssi

    Hi Suleiman, This really helped me. Thank you so much.

    Now I have a question. I have used NestedScrollView instread of RecyclerView and I want to listen the scroll event (and scroll direction) of NestedScrollView. Can you please help pe find out how can I do this?

  • myssi

    Hi Danny, I am also facing this issue. Can you please explain how you fixed it?

    • @yousufsohail:disqus create a directory named values-v21 and inside put a styles.xml file where you extend the basetheme of your app like this

      @color/brown_500
      @color/brown_700
      @color/teal_500
      false

      This is what I used.. Adapt it to your needs

  • Zaier

    Hello !
    is there a technique to put the same toolbar with its background image for a large tablet without loosing scratching this image ? In other question is there any technique to force this image to get a e.g: max-width=450dp
    thanks

    • Yes you can. Simply let the Toolbar belong to the Fragment (which holds the CoordinatorLayout and everything else). From here, if need be you can make that Toolbar behave as the Activity’s ActionBar.

  • Can I do this with ListView?
    Tried but failed.

    • Its tested to work with a NestedScrollView or RecyclerView. So please migrate to either one.

    • myssi

      Anil, have you been able to do this with ListView?

      • No. I had to use ObservableScrollView library. The library is complicated but I figured out how to do this in 3 days (as I am a newbie).

        • Nice work Anil. But if I may add, I’ve personally used that library and its Quick Return pattern is nowhere near good as what the Design Support library provides 🙂

          You might want to compare the two in parallel to see what I mean.

  • Pingback: Handling scroll of AppBarLayout not working(ToolBar doesn't collapse) - BlogoSfera()

  • Sikandar Iqbal

    hey suleiman i have added this animated toolbar in my project but im haivng some issues with the title .. i want to change the size of text in title bar ..plz tell me how can i overcome this issue. thanks

    • Hi Sikandar,
      You can use the ‘expandedTextAppearance’ and ‘collapsedTextAppearance’ attributes to change the title styles.

      • Its ‘expandedTitleTextAppearance’

        • Thanks for the correction.

          • You replied.. wow. Thanks for this nice tutorial. I’m about to use the ksoichiro library, then I saw this. Awesome.

          • You’re welcome.
            That library was a great choice prior to design support. I’ve personally used that too, but I feel the support library does a better job with the animations 😉

  • dhanushka

    i am using android volly libry so i want lord image in this ,,but how i do this????

    • Use a listener to check if an image is set in your header ImageView. After that you can trigger the Palette Async.

      However, if the loading happens slow, use the original thumbnail image Bitmap to pass to Palette. THEN, load a better res image.

  • Kunal Goyal

    can the scrolling be more smooth like in whatsapp ?

    • Are you referring to the snapping when the Toolbar collapses? Actually its gotten a lot better in the latest library update. So I suggest you do the same 🙂

  • adrien3d

    How could I set onClick listeners on tab elements, to start a new activity depending on what item is clicked ?
    I assume you set this case with setOnItemClickListener or OnItemClickListener

    • You must not use a click listener on a Tab to open a new Activity. That is simply wrong. Tabs are used to sub categorize a common topic. Maybe a button click or list item WITHIN a Tab fragment can be used to launch a new Activity.

  • Pingback: CoordinatorLayout view isn’t scrooling with full height header « news-Knowlage FeeD()

  • Saurabh Panchal

    hi @suleiman19:disqus When I am changing the image in imageview(the one in collapsing toolbar) in my java code but whenever I rotate the phone,the image vanishes and restores previously set image.How can I solve this?Thanks.

    • Hi Saurabh,
      How are you setting the image? I need to take a look at your code.

      • Saurabh Panchal

        Hi, @suleiman19:disqus I Solved it. I was setting photo by selecting from gallery(java) but whenever phone went to landscape mode,the activity was getting destroyed and recreated .That’s why I was losing my image. Solved it.Thanks.

        • That’s awesome Saurabh!
          Great job on solving the issue on your own.

  • Hi Vineet,

    You have already got a perfect reply on StackOverflow. Please follow the same and let me know if it worked. If you’re having issues with AppCompat, this should help you: http://blog.grafixartist.com/android-material-design-tutorial/

    • Vineet

      1.) I can’t go with the NoActionBar appcompat theme as I need an action bar in other activities. What do I do?
      2.) I want to integrate this code with a Scrollview where I have some data for that certain activity. Where shall I put this scrollview? should it come in place of the recyclerview or outside the CoordinatorLayout?

    • Vineet

      Hi Suleiman,
      I finally got it to work. But the collapsing toolbar does not shrink or expand in size when I scroll the main scrollview in my activity.(I replaced recyclerview with the scrollview). It only changes size when I specifically shrink or expand the toolbar only.

      • Hi Vineet,

        Replace your ScrollView with a NestedScrollView for it to work properly.

        And the Actionbar you’re talking about must be replaced with a Toolbar. Read the post I’ve linked in my previous comment. The Toolbar is a flexible view that can be setup to behave as an Actionbar.

  • Acp Vinay Kumar

    can we modify this code like whatsapp parallax scrolling which dynamically changes both collapasable toolbar color aswell as status toolbar color from matching image color using palatee

    • WhatsApp uses the ‘Flexible Space with Image Pattern’. Same as what’s being covered in this tutorial
      Everything you ask for is already here. Please go through the post.

  • Pingback: Improving the TripAdvisor Flights experience on AndroidTripAdvisor Engineering Blog()

  • jubby2000

    I know this is probably a pretty dated comment, but I wanted you to know that your post really helped me clear out a lot of errors in my layout. Thanks!

  • I am using single activity with fragments. I have implemented this toolbar animation in activity layout and it is working great. Now for some fragments, I want to disable the CollapsingToolbarLayout (just to show a collapsed toolbar). How can I achieve this?
    I am using v23.1.1

  • Jan

    how to change the toolbar color if its collapse?

  • Pingback: Setting RecyclerView scrolling position on Android - HTML CODE()

  • Jan

    how to set toolbar when collapsed to theme color?

    • Not sure I follow what you meant Jan. Do specify?

  • Kushminder Garg

    I want this type of animation which you have shown in updated version. can you please share code

    • Source code is available via GitHub (link at end of post)

  • Jan

    i followed your code at github but the output in my project is this

    • Jan

      but in your code at github the status bar is this. please help me.

    • Jan

      @suleiman19:disqus help sir

    • Check your styles.xml against mine.

      • Jan

        thanks sir 😀 such a great help 😀 in styles v21 i forgot to check

  • M Mansoor Ali

    hi, when i scroll to the top of the RecyclerView fast (like a fling), the collapsing toolbar does not get down…

    • Hi there,
      Are you referring to the snapping behavior? You can do that by adding ‘snap’ to your Toolbar’s app:layout_scrollFlags property.

  • Aiman Baharum

    Thanks man great work keep it up

  • Rizky Nofriwandi

    hey suleiman, nice tutorial..

    it’s posibble to make this toolbar animation with older sdk version like 16 Jelly bean..
    cause when i make it it’ll give me error on activity_pager on imagebutton which ic_chevron just for min sdk 21.. could u tell me what i’ve to do to make it enable with dk 16..? help me.. thanks

    Best Regards..

  • ImageView header = (ImageView) findViewById(R.id.header);.. You have not used this variable image

    • That’s true Benson. It’s simply a reference. Since the image is static, I’ve set it via XML.
      However, if it was dynamically fetched, you’ll need the variable. 🙂

  • Wiliam

    Hi guys, I have a problem.
    When I give a slap back to the top of the list collapsing toolbar not automatically expands.
    I need the collapsingtoolbar has the same behavior playstore