简体   繁体   中英

How to set app:layout_scrollFlags for Toolbar programmatically

My app have a viewpager and 4 tabs, each tab have many fragment. But I just want my Toolbar scroll up/down while scrolling recyclerview in 2 specific tabs. But I don't know how to block Toolbar scroll for other tabs. I tried to import toolbar for each fragment but it seems I can't do it. Anyone have idea to solve this problem?

I'd strongly recommend against changing the scrolling flags based on what tab is selected - having the Toolbar automatically return (and the content move down) when scrolling to a non-recyclerview tab can be very jarring and probably not an interaction pattern you want (exasperated if your two RecyclerView tabs are next to one another).

However, if you want to see it in person, you can use setScrollFlags() to set the scroll flags programmatically:

Toolbar toolbar = ... // your toolbar within an AppBarLayout
AppBarLayout.LayoutParams params = 
    (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
    | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);

In order to clear flags

params.setScrollFlags(0)
// Show toolbar when we are in maps mode
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
CoordinatorLayout.LayoutParams appBarLayoutParams = (CoordinatorLayout.LayoutParams) mAppBarLayout.getLayoutParams();
if(isMapIndex) {
    params.setScrollFlags(0);
    appBarLayoutParams.setBehavior(null);
    mAppBarLayout.setLayoutParams(appBarLayoutParams);
} else {
    params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
    appBarLayoutParams.setBehavior(new AppBarLayout.Behavior());
    mAppBarLayout.setLayoutParams(appBarLayoutParams);
}

Kotlin version for easy copy&paste. Should work with core-ktx-1.8.0 lib

private fun SomeLayoutBinding.setScrollBehavior(enabled: Boolean) {
    appBarLayoutParams.updateLayoutParams<AppBarLayout.LayoutParams> {
        scrollFlags =
            if (enabled) AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS
            else 0
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM