How To Disable Or Lock CollapsingToolbarLayout Collapse Or Expand

March 11, 2018

I can’t use null for AppBarLayout.scrollFlags because I want to expand and collapse AppBarLayout by code (AppBarLayout.setExpanded). I just don’t to allow users’ interactions to expand or collapse the CollapsingToolbarLayout/AppBarLayout.

Use the following code to prevent scrolling of RecyclerView or NestedScrollView from expanding or collapsing the CollapsingToolbarLayout.

// scrollView can be RecyclerView or NestedScrollView
ViewCompat.setNestedScrollingEnabled(scrollView, false)

User still can expand or collapse CollapsingToolbarLayout by flicking the AppBarLayout. To prevent this from happening, use the following code.

val params = appBar.layoutParams as CoordinatorLayout.LayoutParams
if (params.behavior == null)
    params.behavior = AppBarLayout.Behavior()
val behaviour = params.behavior as AppBarLayout.Behavior
behaviour.setDragCallback(object : AppBarLayout.Behavior.DragCallback() {
    override fun canDrag(appBarLayout: AppBarLayout): Boolean {
        return false
    }
})
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.