Search code examples
androidandroid-coordinatorlayoutandroid-appbarlayout

How to capture the scroll event in CoordinateLayout in Android


I have two toolbars( one set as "enterAlways" and the other is "scroll") and a recyclerview in a coordinatelayout, what I wanted to achieve is to capture scroll event when the recyclerview has not been scrolled, which means when the toolbar which has been set as "enterAlways" is still scrolling.

But when I tried coordinateLayout.setOnScrollChangeListener() , its not working at all.

my layout is like this:

<android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/list_wrapper">

    <EndlessRecyclerView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#00ff0000"
        >
        <include      app:layout_behavior="com.viki.android.adapter.AbsListener"
            android:id="@+id/header_upper" layout="@layout/inlcude_channelheader_upper" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_scrollFlags="scroll"/>
        <include android:id="@+id/header_lower" layout="@layout/include_channelheader_lower" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_scrollFlags="enterAlways"/>

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

How exactly can I capture the scroll event and also the value for dx and dy like what onScrollListener for listview or recyclerview does.


Solution

  • AppBarLayout provides a listener you can implement to listen for when the AppBarLayout's scrolling siblings move up/down. What you want to do is implement that listener and register it with your AppBarLayout as follows:

     mAppBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
    
                Log.d("tag_scroll", "recycler_view current offset: "+verticalOffset);
            }
        });