Programmatically collapse or expand CollapsingToolbarLayout
Asked Answered
H

11

185

Simple question, but I can't find an answer. How can I collapse or expand the CollapsingToolbarLayout programmatically?

collapsed toolbar

↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

expanded toolbar

Hilariahilario answered 4/6, 2015 at 23:33 Comment(2)
I was wondering the same thing. It could also be interesting to expand the toolbar to fullscreen once a user clicks on the embedded layout (eg image).Waterline
I was a little lost with the answers which are omitting the fact that CollapsingToolbarLayout cannot expand or collapse itself what's worst, other comments are making it seemed as if it's an issue that has to do with the version, In reality what you need to handle is its parent, which is funny because CollapsingToolbarLayout CAN disable its own collapse/expansion, but for some reason it cannot trigger them.Multiply
F
383

Using Support Library v23, you can call appBarLayout.setExpanded(true/false).

Further reading: AppBarLayout.setExpanded(boolean)

Firing answered 21/8, 2015 at 9:43 Comment(5)
Ok,thank you for the tip, but support libs v23 are very buggy, so I can't to test it now, because I need to stay on 22.2.1....Hilariahilario
Now you have 23.0.1 with some fixesBerkelium
Is it possible to define a custom animation with support libs 23.1.1? setExpanded(boolean, true) hav a really slow animation...Garbanzo
I had an issue where I have a layout with a collapsible toolbar and an recyclerview under it. When deleting items from the recyclerview the toolbar did not behave appropriately, so i would expand the app bar layout and it worked properly. I ended up using the appBarLayout.setExpanded(true, true) for the animation.Shanney
This only partly expands/collapses the AppBarLayout. There's also a nested CoordinatorLayout to deal with.Dispensatory
L
48

I use this code for collapsing toolbar. Still cannot find a way to expand it.

public void collapseToolbar(){
    CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appbarLayout.getLayoutParams();
    behavior = (AppBarLayout.Behavior) params.getBehavior();
    if(behavior!=null) {
        behavior.onNestedFling(rootLayout, appbarLayout, null, 0, 10000, true);
    }
}

Edit 1: The same function with negative velocityY but the toolbar is not expanded 100% and false for last param should work

public void expandToolbar(){
    CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appbarLayout.getLayoutParams();
    behavior = (AppBarLayout.Behavior) params.getBehavior();
    if(behavior!=null) {
        behavior.onNestedFling(rootLayout, appbarLayout, null, 0, -10000, false);
    }
}

Edit 2: This code do the trick for me

public void expandToolbar(){
    CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appbarLayout.getLayoutParams();
    behavior = (AppBarLayout.Behavior) params.getBehavior();
    if(behavior!=null) {
        behavior.setTopAndBottomOffset(0);
        behavior.onNestedPreScroll(rootLayout, appbarLayout, null, 0, 1, new int[2]);
    }
}
  • setTopAndBottomOffset do expand the toolbar
  • onNestedPreScroll do show the content inside expanded toolbar

Will try to implement Behavior by myself.

Leidaleiden answered 10/6, 2015 at 4:45 Comment(8)
Edit 1 will also work if you set the the last parameter of onNestedFling to false.Piccaninny
params.getBehavior() is returning null. In xml, layout_behaviour tag is set on sibling NestedScrollView, not the AppBarLayout. Can you help me?Athenian
Thank you. Edit 1 work properly, if last param is false. :)Monecious
@GobletSky I faced the same problem. I had NestedScrollView in my fragment and tried to call onNestedFling before set the fragment. After set the fragment, I could call the method successfully.Embosom
@Embosom Actually, my problem was entirely different(somewhat noobish mistake). See this: #31067582Athenian
Working or not, this is more a workaround than a proper solution, you shouldn't rely on the behavior internals to collapse or expand the toolbar.Vaas
Edit 1 and Edit 2 all not work in com.android.support:design:27.0.0Sememe
Edit 2 onNestedPreScroll is deprecated, from what I saw you need to supply another parameter type but after seeing the source code I didn't get where they used itForseti
P
34

You can define how much it expands or collapses with your custom animator. Just use the setTopAndBottomOffset(int).

Here is an example:

CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appBar.getLayoutParams();
final AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
if (behavior != null) {
    ValueAnimator valueAnimator = ValueAnimator.ofInt();
    valueAnimator.setInterpolator(new DecelerateInterpolator());
    valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            behavior.setTopAndBottomOffset((Integer) animation.getAnimatedValue());
            appBar.requestLayout();
        }
    });
    valueAnimator.setIntValues(0, -900);
    valueAnimator.setDuration(400);
    valueAnimator.start();
}
Propinquity answered 5/4, 2016 at 2:19 Comment(5)
This is the only answer that actually let you animate to a custom offset. Many thanks!Trumpeter
appBar.setExpanded(false, true); (open/close, animate) You don't need to write all those linesRaveaux
to @Puni, if you want to expand / collapse to a "custom" offset (like doing multiple stages collapsing), you'll need this.Dortch
This is the best solution to animate AppBar offset in case u don't want to write custom behavior. The one update to the code snippet is to call valueAnimator.setIntValues() with behavior.topAndBottomOffset start value instead of 0 to start animate from current appbar offset.Waftage
To use a custom variable ( -900 ) to set valueAnimator.setIntValues The beter solution is that to use - ( appBar.getTotalScrollRange() )Antidisestablishmentarianism
S
12

I've written a small extension to AppBarLayout. It allows for expanding and collapsing of the CollapsibleToolbarLayout both with and without animation. It seems to be doing it quite right.

Feel free to try it out.

Just use it instead of your AppBarLayout, and you can call methods responsible for expanding or collapsing of the CollapsingToolbarLayout.

It's working exactly as expected in my project, but you might need to tweak the fling/scroll values in the perform... methods (especially in performExpandingWithAnimation()) to fit perfectly with your CollapsibleToolbarLayout.

Solvolysis answered 23/6, 2015 at 8:50 Comment(1)
@ssdeno please read the Readme.md of the Github gist. It's deprecated since v23 of the Support library. Since the v23 of Support (proceeding to AndroidX), there is setExpanded method in the AppBarLayout.Solvolysis
M
8

Use mAppBarLayout.setExpanded(true) to expand Toolbar and use mAppBarLayout.setExpanded(false) to collapse Toolbar.

If you want to change CollapsingToolbarLayout height programmatically then just use mAppBarLayout.setLayoutParams(params);

Expand:

CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) mAppBarLayout.getLayoutParams();
params.height = 3*200; // HEIGHT

mAppBarLayout.setLayoutParams(params);
mAppBarLayout.setExpanded(true);

Collapse:

CoordinatorLayout.LayoutParams params =(CoordinatorLayout.LayoutParams) mAppBarLayout.getLayoutParams();
params.height = 3*80; // HEIGHT

mAppBarLayout.setLayoutParams(params);
mAppBarLayout.setExpanded(false);
Mclaren answered 24/3, 2017 at 4:12 Comment(0)
C
5

for the ones who wants to work with onNestedPreScroll and get error like me. i get NullPointerException in onCreate with out this line

    CoordinatorLayout coordinator =(CoordinatorLayout)findViewById(R.id.tab_maincontent);
    CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
    //below line
    params.setBehavior(new AppBarLayout.Behavior() {});

and doesn't work properly with this. but i work around this problem with

in onCreate :

        scrollToolbarOnDelay();

and...

    public void scrollToolbarOnDelay() {
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.tab_appbar);
                    CoordinatorLayout coordinator = (CoordinatorLayout) findViewById(R.id.tab_maincontent);
                    CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
                    AppBarLayout.Behavior behavior = (AppBarLayout.Behavior) params.getBehavior();
         if(behavior!=null)
                    behavior.onNestedPreScroll(coordinator, appBarLayout, null, 0, 100, new int[]{0, 0});
         else
            scrollToolbarOnDelay()
                }
            }, 100);


        }
Carlinecarling answered 18/4, 2016 at 4:40 Comment(0)
E
5

Try this...

Expand

appBarLayout.setExpanded(true, true);

To recall

appBarLayout.setExpanded(false, true);
Eulaheulalee answered 13/5, 2019 at 5:38 Comment(1)
Amongst all the solution available, this worked for me!!Raja
O
3

To expand/collapse AppBarLayout programmatically:

fun expandAppBarLayout(expand: Boolean, isAnimationEnabled: Boolean){
    appBarLayout.setExpanded(expand, isAnimationEnabled);
}
Oscar answered 20/11, 2019 at 11:8 Comment(0)
E
1

This may help to expand or collapse :

appBarLayout.setActivated(true);
appBarLayout.setExpanded(true, true);
Errolerroll answered 1/2, 2019 at 11:42 Comment(0)
B
0

i have using this

 private fun collapseAppbar() {
        scrollView.postDelayed(Runnable {
            scrollView?.smoothScrollTo(50, 50)
        }, 400)
    }
Bestiality answered 15/5, 2019 at 15:58 Comment(0)
T
0

Make sure your parent is a coordinator layout, otherwise setExpanded will not work.

Temporal answered 3/3, 2023 at 9:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.