Search code examples
androidandroid-coordinatorlayout

Adjusting CoordinatorLayout behavior


Let's assume that we have the following 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.support.v7.widget.SearchView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"/>
    </android.support.design.widget.AppBarLayout>
    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

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

In this layout, if I drag the SearchView upward, it will collapse and disappear. But I wonder how I can attach this dragging effect to my RecyclerView. Means I like to collapse the SearchView whenever I scroll RecyclerView items upward, but expand SearchView when I scroll RecylcerView items downward. Do I need to create a custom behavior for SearchView or it is possible to create this effect by available behaviors?

Best Regards


Solution

  • Use a collapsing toolbar layout and wrap up the searchView inside it... and also wrap up the recyclerView with a nestedScrollView and add the app:layout_behavior="@string/appbar_scrolling_view_behavior"/> to the nested scroll view instead

    Dont forget to add scrollFlags and content_scrim to your collapsing toolbar layout..

    The collapsing toolbar layout should be inside the appBarLayout

    For reference check this out

    https://antonioleiva.com/collapsing-toolbar-layout/