I am trying to implement a ViewPager-like behavior for a horizontal RecyclerView
. The data from the adapter should inflate and bind as normal, but the navigation through the Recycler
should be handled differently. When the user swipes (or attempts to scroll), I move the Recycler
one item in that direction, sticking it to the left side.
I already have all the item transition logic. I am using a custom LayoutManager
, which overrides onSmoothScrollToPosition()
with a custom LinearSmoothScroller()
which does the item to-the-left sticking.
The question is - how can I override the scrolling behavior of the RecyclerView
to intercept the swipes and handle them myself? I tried disabling scrolling in the LayoutManager
and then intercepting the gesture in an onTouchListener
, but this does not seem to work. Does the RecyclerView
framework have a clean way to handle this?
OnFlingListener . LinearSnapHelper or PagerSnapHelper are concrete implementations of SnapHelper . They offer most of the functionality needed to implement your custom SnapHelper . Consider extending one of these to suit your needs. For example, LinearSnapHelper snaps to the view closest to the middle of the parent.
basically in ViewPager you can scroll only one item at time (either left or right), and in RecyclerView you can scroll to any index. it all depends on your requirements how you want to use it.
ViewPager2 comes with right-to-left support, orientation changes, now you can use RecyclerView with ViewPager which can enable usage of DiffUtils, LayoutManager, PageTransformations, Fragments as pages which are modifiable etc.
The native Android solution covered in this post was a super easy way to get the RecyclerView to behave like a ViewPager.
Relevant bits:
The 24.2.0 version of the support library introduced two new classes (SnapHelper and LinearSnapHelper) that should be used to handle snapping in a RecyclerView. .... The only code needed is:
SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
SnapHelper snapHelper = new GravitySnapHelper(Gravity.START);
snapHelper.attachToRecyclerView(startRecyclerView);
there is a library layoutmanagers exactly for this.
the one that you need is ViewPagerLayoutManager. It is based on the same idea you already have but more extended and handles multiple cases. It basically scrolls until there is a change of page & state then takes over and adjust to the right page.
To use it you just need to set it as a normal Layout manager:
recyclerView.setLayoutManager(new ViewPagerLayoutManager(getActivity()));
for more info and examples check here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With