Pager-like behavior in RecyclerView

I am trying to implement a ViewPager-like behavior for a horizontal RecyclerView . Data from the adapter should be inflated and bound as usual, but switching through the Recycler should be done differently. When the user scrolls (or tries to scroll), I move the Recycler one element in that direction, holding it to the left.

I already have all the element transition logic. I am using a custom LayoutManager that overrides onSmoothScrollToPosition() with a custom LinearSmoothScroller() that makes the item to its left.

Question: how can I cancel the RecyclerView scroll behavior to intercept swipes and handle them myself? I tried disabling scrolling in the LayoutManager and then intercepted the gesture in onTouchListener , but this does not seem to work. Does the RecyclerView structure have a clean way to handle this?

+5
source share
3 answers

There is a library of layoutmanagers for this.

the one you need is ViewPagerLayoutManager . It is based on the same idea that you already have, but more advanced and handle several cases. It basically scrolls until the page and status change, and then goes to the correct page.

To use it, you just need to install it as a regular layout manager:

 recyclerView.setLayoutManager(new ViewPagerLayoutManager(getActivity())); 

for more information and examples check here

+2
source

The natural Android solution covered by this was a super easy way to make RecyclerView behave like a ViewPager.

Matching bits:

In the support library version 24.2.0, two new classes were introduced (SnapHelper and LinearSnapHelper), which should be used to handle bindings in RecyclerView ..... The only code needed:

SnapHelper snapHelper = new LinearSnapHelper(); snapHelper.attachToRecyclerView(recyclerView);

SnapHelper snapHelper = new GravitySnapHelper(Gravity.START); snapHelper.attachToRecyclerView(startRecyclerView);

+2
source

Set RecyclerView LayoutManager to

final StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL); mRecyclerView.setLayoutManager(layoutManager);

0
source

Source: https://habr.com/ru/post/1246132/


All Articles