Reputation: 7527
I have a screen where i need to display a toolbar at the top, a slideshow below the toolbar and a recyclerview below the slideshow. For displaying the slideshow I am using a viewPager which slides images horizontally.
The problem I am currently facing is that when the recyclerview is scrolled the viewPager needs to scroll with it and the toolbar should stay pinned.
I tried putting the viewPager and the recyclerview inside a nested Scroll but since a nested scroll requires a single child i had to put both the viewpager and recyclerview inside a linear layout because of which the scrolling behaviour of the recyclerview went for a toss ( i am monitoring the recyclerview scroll so i can load more results when it reaches the bottom ).
Upvotes: 0
Views: 656
Reputation: 54234
You can solve this problem by using CoordinatorLayout
, AppBarLayout
, and CollapsingToolbarLayout
. You put your Toolbar
and ViewPager
in the CollapsingToolbarLayout
, and you use the RecyclerView
as the scrolling sibling to the AppBarLayout
so that it can correctly collapse the ViewPager
.
Here's some example XML I used to achieve what I think you described:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="?attr/actionBarSize"/>
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_collapseMode="pin"/>
</android.support.design.widget.CollapsingToolbarLayout>
</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"
app:layoutManager="LinearLayoutManager"/>
</android.support.design.widget.CoordinatorLayout>
The only tricky bit is that the <Toolbar>
tag has to come after the <ViewPager>
tag, since they're both inside a view that derives from FrameLayout
. Normally, this would mean that the toolbar obscures the top portion of the viewpager, but the viewpager's marginTop
attribute stops that from happening.
Upvotes: 2