Toolbar Animation with Android Design Support Library

In this Android tutorial we’ll create an on scroll, collapsing Toolbar animation.

The Design support library for Android makes it easy to create great animations. Let’s look at how to create an app with a collapsing Toolbar animation. It’s know as Flexible Space with Image pattern, a popular scrolling technique.

I didn’t know this pattern actually had a name until Ian Lake happened to point it out for me.

Flexible Space with Image Pattern

A scrolling technique that supports an image header with a scrollable view below it. Upon scrolling, the ‘Flexible Space’ (image header) gets tinted with or. At the same time, it collapses into a Toolbar – Material Design guidelines

This pattern is a popular scrolling technique. In familiar terms, you can see this in WhatsApp’s contact detail screen.

Here’s the step-by-step screenshots of the Flexible Space animation. Should give you a clear picture of what’s going on.

icon icon

Flexible Space with Image Pattern – step by step

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

We can do this with the Palette API, but more on that later.

You might immediately start to freak out with the amount of code it might take. But rest assured, there’s no scary Java code to write. Most of it is XML, so cheers to that!

Update: This article has been updated for Support Library v25.2.0. It also includes best practices for using the Flexible Space Pattern correctly.

Other Design Support Library tutorials:

Here’s a useful index for navigating the article. Sections include not just how to implement the pattern. But also how to do it correctly, in terms of UI and UX.


  1. Getting Started
    1. Layout Structure
    2. Design Support UI Widgets
    3. Defining the XML Layout
      1. TIP: Use a Scrim for clear, readable Text
    4. Getting the Parallax Scroll right
  2. Floating Action Button
    1. The Hidden Action
    2. Updating Toolbar Menu
  3. Dynamic Colors with Palette API
    1. Using the Palette API
  4. Complete Activity Code
  5. Toolbar Animation in Action

Getting Started

Start by adding the Design Support Library to your app/build.gradle file.

dependencies {
    compile ''

Layout Structure

As always, we’ll get started with the XML first. Open your activity.xml layout.

Here’s the layout skeleton.

< >

    < >

        < >

            <ImageView />

            < />

    <!-- Your scrollable content here -->


Design Support UI Widgets

I understand if all these layouts might appear new to you. But you won’t have to worry. I’ll do my best to explain them, in the easiest way.

1. CoordinatorLayout

A powerful FrameLayout that specifies behavior for child views for various interactions. It also allows anchoring of floating views in your layout.

2. AppBarLayout

It is a special kind of vertical LinearLayout. It helps respond to its children’s scroll events (scroll gestures). Additionally, it’s responsible for implementing many features of Material Design’s AppBarLayout.

But, there’s one thing to note. Its usage relies on being a direct child within CoordinatorLayout. The layout skeleton above demonstrates this.

3. CollapsingToolbarLayout

It is a Toolbar wrapper which makes the ‘Flexible Space’ pattern possible. It collapses the image header while decreasing the expanded title to a Toolbar title.

What’s left is the ImageView which holds our actual header’s image and Toolbar which we’re familiar with.

4. FloatingActionButton

I’m sure you’re familiar with what a Floating Action Button is, aren’t you? Android gave it a thumbs up by giving us an official UI widget. It’s a part of the Design Support Library.

More on this later.

Defining the XML Layout

Alright, with that out of the way lets get to the actual XML.

A word of caution. The layout below might look threatening in size!

This is not complex code. XML just tends to be a little verbose. But you’re welcome to try replicating the Flexible Space scroll animation in Java. Then I’m sure you’d truly appreciate how easy the Design Support library is.

However, I have highlighted the essential lines you need to focus on.

What you need to know from this?
  • line 24: layout_scrollFlags
    Tells the CollapsingToolbarLayout and its children, how to behave on a scroll.
    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-screen. For views that do not use this flag, they’ll remain pinned to the top of the screen.
    • exitUntilCollapsed:
      causes the view to scroll off until it is ‘collapsed’ before exiting
    • snap:
      enables the expanded view to snap to either a collapsed state, or expanded state. There is no in-between state. If the View has been dragged more towards expanding, it expands completely. If its dragged more towards collapsing, the View collapses completely.
  • line 33: layout_collapseMode
    Indicates how the ImageView reacts while collapsing on-scroll.
    There are 2 collapse modes:

    • COLLAPSE_MODE_PARALLAX (use for ImageView)
    • COLLAPSE_MODE_PIN (use for Toolbar)
  • line 63: layout_behavior
    The CoordinatorLayout performs most of its magic using Behavior. Behaviors tell how its child Views must interact with each other.
  • line 73: layout_anchor
    Remember we spoke about anchoring Views earlier? This attribute tells FloatingActionButton to anchor’ itself to AppBarLayout.
  • line 74: layout_anchorGravity
    This attribute tells our View where to display, on its anchor View.

Here’s what the Android Studio’s Preview pane shows us.

Flexible Space with Image Pattern – XML Layout Preview

But wait. Does the expanded title look clear enough to you? I’m sure it’s not.

Whenever you display a label (TextView) against a background image, use a ‘scrim‘. It will help make the text more readable.

TIP: Use a Scrim for clear, readable Text

A Scrim is a semi-transparent gradient layer that helps Text appear more readable against backgrounds.

Just below your ImageView, add a simple View with a gradient Drawable as background.


Here’s the Drawable scrim.

<shape xmlns:android=""

See the difference for yourself.

Header without and with Scrim

While the difference is subtle, the latter is much better right? Additionally, you can apply another scrim for the Toolbar. It can help the back and overflow icons be more visible. I leave this as an exercise for you.

Getting the Parallax Scroll right

I’ve already mentioned a hint above on parallax scroll. But there’s more to it. We can achieve parallax scrolling with ImageView by setting its layout_collapseMode to parallax.

Parallax Scrolling involves the background moving at a slower rate to the foreground. –

Did you notice an extra collapse mode attribute for the Toolbar? Yes, you must use this as well. Why? Because, while the ImageView should collapse, the Toolbar must persist on scrolling.

Toolbar must use collapseMode:pin, because we want it to persist and remain on top, as the user scrolls down.

Note that I haven’t set any color for the Toolbar. The CollapsingToolbarLayout takes care of this. It dynamically picks up a color from our image and sets it to the Toolbar.

Floating Action Button

Let’s look at the Floating Action Button for a bit. I’ll stick to calling it FAB from now on. If you tried to create a FAB earlier, you’d realize how hard it was. Yes, my previous posts on the FAB are now redundant. Sigh.

But with the Design Support Library, that’s not the case anymore. The layout above shows, how easy it is!

Notice that I haven’t explicitly defined a size for the FAB. By default, it takes its regular width and height of 56dp. But, you can define this by using the following attribute.


Optionally, you can set the fabSize as mini, which is a miniature version of the FAB at 40dp in size.

Next, in the layout, we position the FAB with alignment to the AppBarLayout. We do this with the layout_anchor attribute.

        app:layout_anchorGravity="bottom|right|end" />

FAB without and with anchor attribute

That’s a wrap for the XML part. The good news is, this XML is all that’s required to trigger the Flexible Space scroll animation.

But wait! There’s still one thing that seems a bit off. What about the FAB’s action? After scrolling, the action goes hidden. It becomes available, only when you scroll, all the way to the top.

The Hidden Action

Once the AppBar collapses, we need to show the FAB’s action somewhere.

Now I’m not saying this is the recommended approach. But my suggestion is that once the FAB vanishes, we add the action to the Toolbar’s menu.

Dynamic Toolbar Menu item

To do this we’ll need a listener first. We have to listen to the when the AppBarLayout expands and collapses. To be precise, we need an OffsetChangedListener.

If the AppBarLayout’s ‘verticalOffset’ is zero, then its fully expanded. So when the verticalOffset is almost equal to the fully expanded height, add the action to Toolbar’s menu.

First, let’s look at how to set the listener. Here’s how to do it.

appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                //  Vertical offset == 0 indicates appBar is fully expanded.
                if (Math.abs(verticalOffset) > 200) {
                    appBarExpanded = false;
                } else {
                    appBarExpanded = true;

Here are some key takeaway points from the above code snippet.

  1. verticalOffset returns negative values, so we wrap it with Math.abs(verticalOffset)
  2. appBarExpanded is a boolean flag that I’m maintaining to know when AppBarLayout is expanded or collapsed
  3. invalidateOptionsMenu() is called every time our AppBarLayout’s height crosses a threshold (200)

Now I wish there was a simpler way to know the AppBarLayout’s state. But I guess this solution works good enough.

Updating Toolbar Menu

invalidateOptionsMenu() helps update our Toolbar Menu. But we need to tell our Menu when to add and remove our extra Action.

Note that the FAB’s action is an ‘Add’ function.

First, we need a reference for the existing Menu. You can get this from the onCreateOptionsMenu() method.

  public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(, menu);
      collapsedMenu = menu;
      return true;

collapsedMenu is a global variable of type Menu. It allows us to keep a copy of the original Menu.

Next, we need to update our Menu. We’re already calling invalidateOptionsMenu() in the scroll listener. This will trigger the onPrepareOptionsMenu() method. Hence, we’ll add our dynamic Menu logic here.

    public boolean onPrepareOptionsMenu(Menu menu) {
        if (collapsedMenu != null
                && (!appBarExpanded || collapsedMenu.size() != 1)) {
        } else {

        return super.onPrepareOptionsMenu(collapsedMenu);

You’ll notice that I haven’t done anything for the expanded state. We don’t need to either. I’ll tell you why.

After onPrepareOptionsMenu(), the onCreateOptionsMenu() is called. What do we need to do in the expanded state? The FAB becomes visible, which means we should hide the ‘Add’ action from Toolbar menu.

Since onCreateOptionsMenu() inflates the original Menu again, we don’t have to worry about manually removing it.

So now, when the FAB hides, its Action will be added to Toolbar Menu. When the AppBarLayout collapses and FAB hides, the ‘Add’ action becomes visible in the Toolbar Menu.

Now all that remains is to do the usual UI initialization in Java. So let’s setup our Toolbar and then call in the Palette API.

Dynamic Colors with Palette API

The palette API is a support library that extracts prominent colors from images.

To use the Palette library, we first need to add it to your project. So open up your app/build.gradle and add the following line.

dependencies {
    compile ''

Remember that we have to initialize our UI first. So open your and type away. Or copy-paste this instead.

toolbar = (Toolbar) findViewById(;

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

ImageView header = (ImageView) findViewById(;

Now you might ask me, why I have set a title for CollapsingToolbarLayout, instead of Toolbar? That’s a valid question.

Android Material UI Template 8 in 1 CodeCanyon

Take a look at the Flexible Space with Image scroll animation. Yes, the GIF which I shared at the beginning of this post. Notice there’s an expanded title, which on scrolling, collapses into the Toolbar title.

The CollapsingToolbarLayout handles this for us. Hence we set the title for that, instead of a Toolbar.

Additionally, the CollapsingToolbarLayout also handles tinting our Toolbar using the Palette API. I’ll show you how to do this.

Using the Palette API

First, pass the ‘header’ ImageView’s bitmap to the Palette API. Then the API will generate colors based on the header image, in an AsyncTask.

Once it completes, we can fetch a color we want and set it to CollapsingToolbarLayout. This, in turn, tints our Toolbar to our chosen color, when we scroll.

Let’s look at some code.

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
        Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
            public void onGenerated(Palette palette) {
                mutedColor = palette.getMutedColor(R.attr.colorPrimary);

I am fetching my bitmap from my resources directory.

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

The Palette API offers several color options (variations). Here are the basic four:

  • Light
  • Dark
  • Vibrant
  • Muted

Image credits:

You can also increase the number of colors generated from the image. Or you can 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.

Complete Activity Code

Here’s the complete Activity for your reference.

Output – Toolbar Animation Results

Finally, we’ve completed what’s needed for the Toolbar animation. In fact, much more than what’s required! So go ahead, run your app and watch the magic.

Toolbar animation output

To be honest, it was surprising to see such a smooth Toolbar animation. Even the FAB beautifully reacts upon touch with a higher elevation.

Source Code:

View Project on GitHub


Material Design is a powerful visual language that can help you design a brilliant app. The Design Support Library makes it easy to create powerful animations, like this. It allows us to create rich app experiences our users can enjoy.

How are you using the Design Support Library? Do you have your own take on the ‘Flexible Space with Image’ animation pattern? Let me know in the comments below.

Also, if you liked reading this, don’t forget to share with your friends.

Subscribe to stay updated
You'll be first to know about new articles and more. They're sent straight to your inbox!
No Spam, no BS. Promise. You can unsubscribe anytime.

App developer with an eye for design. Loves to create apps with good UI/ UX that doesn’t annoy people. In his spare time, he likes to draw and paint.


App developer with an eye for design. Loves to create apps with good UI/ UX that doesn't annoy people. In his spare time, he likes to draw and paint.

You may also like...

234 Responses

  1. abdul rehman says:

    could you please tell me how to show the scrolling content behind the toolbar.. i want to use an edit text as pinned on top and the scrolling content should be visible behind it while scrolling like in true caller android app(in search section) ??

    • Suleiman19 says:

      Hi Abdul,

      I haven’t used the Truecaller app so I don’t know the animation they’re using.
      However, from what you say, you can add your EditText within your Toolbar layout. Everything else in your layout would remain the same, like how I’ve mentioned it in the post.

  2. Wiliam says:

    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

  3. ImageView header = (ImageView) findViewById(;.. You have not used this variable image

    • Suleiman19 says:

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

  4. Rizky Nofriwandi says:

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

  5. Aiman Baharum says:

    Thanks man great work keep it up

  6. M Mansoor Ali says:

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

  7. Jan says:

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

  8. Kushminder Garg says:

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

  9. Jan says:

    how to set toolbar when collapsed to theme color?

  10. Jan says:

    how to change the toolbar color if its collapse?

  11. Rohit Arya says:

    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

  12. jubby2000 says:

    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!

  13. Acp Vinay Kumar says:

    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

    • Suleiman19 says:

      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.

  14. Vineet says:

    Hi I am facing a lot of issues following this post. I have posted on stackoverflow about it please take a look:

    • Suleiman19 says:

      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:

      • Vineet says:

        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 says:

        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.

      • Suleiman19 says:

        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.

  15. Saurabh Panchal says:

    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.

    • Suleiman19 says:

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

      • Saurabh Panchal says:

        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.

      • Suleiman19 says:

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

  16. adrien3d says:

    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

    • Suleiman19 says:

      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.

  17. Kunal Goyal says:

    can the scrolling be more smooth like in whatsapp ?

    • Suleiman19 says:

      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 🙂

  18. dhanushka says:

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

    • Suleiman19 says:

      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.

  19. Sikandar Iqbal says:

    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

  20. Anil says:

    Can I do this with ListView?
    Tried but failed.

    • Suleiman19 says:

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

    • myssi says:

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

      • Anil says:

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

      • Suleiman19 says:

        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.

  21. Zaier says:

    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

    • Suleiman19 says:

      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.

  22. myssi says:

    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?

  23. lythenas says:

    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.

    • Suleiman19 says:

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

  24. Danny says:

    Any suggestions on this issue? I used your xml, just a few edits and i’m getting that

    • Suleiman19 says:

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

      • Danny says:

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

      • Danny says:

        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

      • Suleiman19 says:

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

      • Danny says:

        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

    • myssi says:

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

      • Danny says:

        @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


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

  25. Arth Tilva says:

    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.

  26. disqustion? says:

    Hi Suleiman, i have a problem . Collapsing is bounce .. just like video

    and stackoweflow

  27. Baris says:

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

  28. Eric says:

    Got an error— CollapsingToolbar cannot be resolved or is not a type despite using this:import;

  29. igoticecream says:

    Excelent tutorial. I was wondering how to make the collapse of the toolbar after reaching certain threshold (like you do to the FAB in another article)? Any clues?

    I was trying to do the same, but the recycler view isnt adjusting to the collapse (there’s a gap between it and the collapsed toolbar :/)

  30. Aman Jham says:

    how to set the sub title in CollapsingToolbarLayout like when user open the group profile in theWhatapp Application, toolbar subtile is also coming?How to add that functionality?

  31. Derrick Ozil Mugenyi says:

    Hey Suleiman, its me again.. I managed to get the gridView working and the Toolbar works properly… But i have one issue how do i make the textView in this example open new intent once clicked…Should it be put under the onClick method in the

  32. Diego Acuña says:

    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?


    • Suleiman19 says:

      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.

  33. Rowan says:

    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?

    • Suleiman19 says:

      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.

  34. Jacek Kwiecień says:

    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

  35. Valerie says:

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

  36. farhan ali says:

    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

  37. guru says:

    Hi, I’m using imageview and custom gridview inside collapsing toolbar layout hwich works fine in devices with version 5.1.1 and not aligned in lower versions. When i try to call layout_gravity=”bottom” it appears at bottom. Could you please explain?

    • Suleiman19 says:

      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

  38. BrandonWhite116 says:

    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.

  39. Aviad Moreshet says:

    First off, really thanks for the tutorial, it actually works & helps alot.

    Second, I tried to make some minor changes (add navigation view and allow scrolling up), but didn’t manage to do that. Could you please take a look here?

    • Suleiman19 says:

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

      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 says:

        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(;
        mLayoutManager = new LinearLayoutManager(this);
        if(mAdapter == null){
        mAdapter = new ProfileAdapter(this, user);
        mRecyclerView.scrollToPosition(mAdapter.getItemCount() – 1);

      • Suleiman19 says:

        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 says:

        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?

      • Suleiman19 says:

        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 says:

        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?

      • Suleiman19 says:

        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:

  40. Mwas says:

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

  41. I can’t compile ‘’ and give the error fail to resolve

  42. Jason Moix says:

    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!

    • Suleiman19 says:

      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 says:

        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!

      • Suleiman19 says:

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


  43. Giuseppe C. says:

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

  44. Ed Foux says:

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

    • Suleiman19 says:

      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?

  45. Prathya says:

    Hello, How can I apply this effect on a listview? I tried replacing recyclerView with listview, but it didn’t work and header remained static.

  46. Santino Wang says:

    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………

    • Suleiman19 says:

      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 says:

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

  47. Tshepo Stark says:

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

    • Suleiman19 says:

      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 says:

        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?

      • Suleiman19 says:

        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 says:

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

      • Suleiman19 says:

        change your colorPrimary in styles.xml

  48. blu says:

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

  49. Ed Foux says:

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

    • Suleiman19 says:

      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.

  50. Andrii says:

    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

  51. Santino Wang says:

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

  52. Pri says: not appearing on toolbar in AnimateToolbar Activity. Please help.

    Any solution, please tell me.

  53. Pri says:

    app:layout_collapseMode=”pin” not working for Toolbar

    Toolbar getting scrolled with recyclerView

    • Suleiman19 says:

      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 says:

        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
        in collapsingToolbarLayout

  54. Robert says:

    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.

    • Suleiman19 says:

      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!

  55. Paritosh Tonk says:

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

  56. Witalo Benicio says:

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

    • Witalo Benicio says:

      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 :/

      • Suleiman19 says:

        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 says:

        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 ‘’
        compile ‘’
        compile ‘’
        compile ‘’
        compile ‘’
        compile ‘’
        compile ‘’

        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 ‘’
        compile ‘com.squareup.okhttp:okhttp:2.3.0’
        compile ‘com.squareup.okhttp:okhttp-urlconnection:2.0.0’
        compile ‘’
        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:’
        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.

      • Suleiman19 says:

        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.


      • Witalo Benicio says:

        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

      • Suleiman19 says:

        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 says:

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

      • Suleiman19 says:

        That’s great Witalo. Awesome!

      • Witalo Benicio says:

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

      • Suleiman19 says:

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

    • Pri says:

      Make sure you’re using , same problem with me, I updated the version and it works

  57. Peter Pan says:

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

  58. panas says:

    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?

    • Suleiman19 says:

      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?

      • panas says:

        yes this

      • Suleiman19 says:

        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 says:

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

      • Suleiman19 says:

        In that case, I suggest you check this out.

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

        If it still doesn’t answer your question, then please try giving a clearer question with a possible sample.

      • Naresh Jain says:

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

      • Jitesh H Lalwani says:

        Just add


      • Avtar Singh says:

        @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”

      • Suleiman19 says:

        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 says:

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

      • Avtar Singh says:

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

      • Avtar Singh says:

        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

      • Suleiman19 says:

        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:


      • Nidhin Vasudev says:

        how can i add subtitle for the collapsingToolbarLayout

      • Suleiman19 says:

        You’ll have to include a TextView inside your Toolbar. This should help:

      • panas says:

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

      • Virat Nirmal says:

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

      • Dhaval P says:

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

      • Suleiman19 says:

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

Subscribe to stay updated
You'll be first to know about new articles and more. They're sent straight to your inbox!
No Spam, no BS. Promise. You can unsubscribe anytime.
Gradle setup, ProGuard rules, Material Design palette, metrics and much more

FREE Material Design Starter Project

For more details, click on the below link.
Download FREE
Material Design Template Project for Android Studio