Search code examples
androidmaterial-designandroid-coordinatorlayoutandroid-appbarlayout

How do I make the RecyclerView stay still when the app bar snaps?


When the AppBarLayout snaps, the CoordinatorLayout scrolls the RecyclerView up. Instead, I want the AppBarLayout snap back into place without changing the scroll position of the RecyclerView. The Google Play Store app has the behavior I am trying to achieve.

How do I accomplish keeping the RecyclerView still while the AppBarLayout snaps?

Here is my layout:

        <?xml version="1.0" encoding="utf-8"?> 
    <android.support.design.widget.CoordinatorLayout  xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/main_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            android:id="@+id/appbar"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_scrollFlags="scroll|enterAlways|snap" />

        </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
                android:id="@+id/rvToDoList"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_behavior="@string/appbar_scrolling_view_behavior" />
  </android.support.design.widget.CoordinatorLayout>

Solution

  • Use Retractable Toolbar

    In your build.grade add:

    compile 'it.michelelacorte.retractabletoolbar:library:1.0.0'
    

    Than in your Activity (change recyclerView and toolbar with yours):

    RetractableToolbarUtil.ShowHideToolbarOnScrollingListener showHideToolbarListener;
    recyclerView.addOnScrollListener(showHideToolbarListener = new RetractableToolbarUtil.ShowHideToolbarOnScrollingListener(toolbar));
    
    if (savedInstanceState != null) {
                showHideToolbarListener.onRestoreInstanceState((RetractableToolbarUtil.ShowHideToolbarOnScrollingListener.State) savedInstanceState
                        .getParcelable(RetractableToolbarUtil.ShowHideToolbarOnScrollingListener.SHOW_HIDE_TOOLBAR_LISTENER_STATE));
    }
    

    Result:

    enter image description here