Programmatically collapse or expand CollapsingToolbarLayout Programmatically collapse or expand CollapsingToolbarLayout android android

Programmatically collapse or expand CollapsingToolbarLayout


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

Further reading: AppBarLayout.setExpanded(boolean)


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.


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