Changing Toolbar and CollapsingToolbarLayout scroll flags programmatically
S

3

15

I have a single Activity android app with lots of fragments. When I'm showing a list screen I want to use the Toolbar with the, app:layout_scrollFlags="scroll|enterAlways" property. And in the detail fragments I want to use the CollapsingToolbarLayout with an image in it. Since it's a single Activity app, I have only one Toolbar. Is it possible to modify my layout programmatically to suit both cases?

Sickler answered 5/9, 2015 at 23:34 Comment(0)
A
16

Yes. Let's say you are going from the CollapsingToolbarLayout fragment to the Toolbar one.

  1. You collapse your AppBarLayout using AppBarLayout.setExpanded(false);

  2. You change the scroll flags to fit your needs.

    AppBarLayout.LayoutParams p = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
    p.setScrollFlags(...);
    toolbar.setLayoutParams(p);
    

    Same goes for the CollapsingToolbarLayout if necessary. I guess it should be something like:

    collapsingToolbarParams.setScrollFlags(0); //no flags for ctl
    toolbarParams.setScrollFlags(SCROLL_FLAG_SCROLL | SCROLL_FLAG_ENTER_ALWAYS); //new flags for toolbar
    
Ademption answered 5/9, 2015 at 23:40 Comment(2)
I also had this problem. Seems that I forgot to call the setLayoutParams() method. Thanks for the answer!Marxist
setScrollFlags(0) works fine but when I try to set it to this: params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP); // clear all scroll flags toolbar.setLayoutParams(params); doesn't work..Wizard
F
11

I found it working

public void disableToolBarScrolling() {
    CollapsingToolbarLayout toolbar = findViewById(R.id.collap_toolbar);
    AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
    params.setScrollFlags(0);
}

public void enableToolBarScrolling() {
    CollapsingToolbarLayout toolbar = findViewById(R.id.collap_toolbar);
    AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
    params.setScrollFlags(SCROLL_FLAG_SCROLL | SCROLL_FLAG_ENTER_ALWAYS);
}
Freund answered 18/11, 2019 at 10:6 Comment(0)
P
0

Works for me.

public void enableToolBarScrolling(CollapsingToolbarLayout toolbar) {
    AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
    params.setScrollFlags(SCROLL_FLAG_SCROLL | SCROLL_FLAG_ENTER_ALWAYS);
    toolbar.setLayoutParams(params);
}
Pentastich answered 17/3, 2021 at 20:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.