Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically collapse or expand CollapsingToolbarLayout

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

collapsed toolbar

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

expanded toolbar

like image 711
Tomas Avatar asked Oct 03 '22 21:10

Tomas


People also ask

How do you collapse a CollapsingToolbarLayout?

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

What is collapsing Toolbar Android?

Android CollapsingToolbarLayout is a wrapper for Toolbar which implements a collapsing app bar. It is designed to be used as a direct child of a AppBarLayout. This type of layout is commonly seen in the Profile Screen of the Whatsapp Application.

How do I disable scrolling in collapsing Toolbar layout Android?

The solution is simple, we just need to set the app:scrimAnimationDuration=”0" in our collapsing toolbar layout like the below code snippet. Now just run the code and see the results, you will see then there will be no fading animation anymore.


2 Answers

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

Further reading: AppBarLayout.setExpanded(boolean)

like image 372
jaxvy Avatar answered Oct 06 '22 09:10

jaxvy


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.

like image 48
Tuấn Trần Anh Avatar answered Oct 06 '22 11:10

Tuấn Trần Anh