CoordinatorLayout using the ViewPager's RecyclerView

Rod_Algonquin picture Rod_Algonquin · May 30, 2015 · Viewed 49.3k times · Source

I am using the view CoordinatorLayout from android.support.design. I want to attach the app:layout_behavior to the fragment's RecyclerView?

In the example given by Google, they only attach it in the RecyclerView of the same XML file where the CoordinatorLayout was attached.

Is there a way to attach CoordinatorLayout to the fragment's RecyclerView within the ViewPager?

The sample is in this blog post at Android Developers blog.

Answer

androholic picture androholic · May 30, 2015

Chris Banes has posted a sample on Github which shows exactly what you want to do.

Here is the xml file that defines how one can indirectly attach a coordinator layout to the viewpager's fragments.

<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:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        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"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

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

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        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"
        android:src="@drawable/ic_done" />

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

The idea is to let the viewpager have the layout_behavior attribute.