Search code examples
androidandroid-recyclerviewcoordinator-layout

RecyclerView and CoordinatorLayout.Behavior


I want to learn how Coordinator Custom behavior works so I've made a project that when a recyclerview scrolls , the button Y scale changes. This is my xml layout :

<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/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/mp_recycleview1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/cardview_light_background"
        android:paddingBottom="5dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:paddingTop="5dp"
        android:scrollbars="vertical" />

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/cardview_dark_background"
            android:backgroundTint="@color/colorPrimary"
            android:text="Button"
            app:layout_behavior=".MyBehavior"
            android:textColor="@android:color/white"
            />
</android.support.design.widget.CoordinatorLayout>

and this is My Behavior class

public class MyBehavior extends CoordinatorLayout.Behavior<Button> {
    private final static String TAG = "MyBehavior";

    public MyBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, Button child, View dependency) {
        return dependency instanceof RecyclerView;

    }

    @Override
    public void onNestedScroll(CoordinatorLayout coordinatorLayout, Button child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
        child.setScaleY(((RecyclerView)target).computeVerticalScrollOffset());


    }
}

But when I scroll the RecyclerView nothing happens.


Solution

  • Heads up here,

    in order to receive onNestedScroll() calls, you need to override onStartNestedScroll to return true.