Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove SnapHelper from a RecyclerView

I use attachToRecyclerView(RecyclerView) and it works as expected.

Question: at some point I want the same recyclerView to scroll normally, how to achieve that?

Code:

PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
pagerSnapHelper.attachToRecyclerView(recyclerView);
like image 690
Belzebub Avatar asked Jul 26 '17 07:07

Belzebub


People also ask

How do I use SnapHelper in RecyclerView?

You can now just use a SnapHelper. If you want a center-aligned snapping behavior similar to ViewPager then use PagerSnapHelper: SnapHelper snapHelper = new PagerSnapHelper(); snapHelper. attachToRecyclerView(recyclerView);

What is a SnapHelper?

SnapHelper is a helper class that is used to snap any child of our RecyclerView. With the help of this class, we can display the specific number of RecyclerView items on our screen, and we can avoid the RecyclerView children's display inside our RecyclerView.


3 Answers

Staring from recyclerview-v7:25.1.0, is enough to call

snapHelper.attachToRecyclerView(null); 

to remove the SnapHelper

I faced the same problem. Calling

clearOnScrollListeners();
setOnFlingListener(null);

on the RecyclerView instance did the trick for me. Calling only setOnFlingListener(null); wasn't enough in my case

like image 61
Blackbelt Avatar answered Oct 11 '22 04:10

Blackbelt


well,it's written on the SnapHelper official API:Public methods=>attachToRecyclerView:[The RecyclerView instance to which you want to add this helper or null if you want to remove SnapHelper from the current RecyclerView.] https://developer.android.com/reference/android/support/v7/widget/SnapHelper.html#attachToRecyclerView%28android.support.v7.widget.RecyclerView%29

like image 27
SunShixiong Avatar answered Oct 11 '22 06:10

SunShixiong


If you don't want to keep the reference of SnapHelper then there is another way around as per the official documentation you can use

recyclerView.setOnFlingListener(null);

From the Android documentaion

  • Attaches the {@link SnapHelper} to the provided RecyclerView, by calling
  • {@link RecyclerView#setOnFlingListener(RecyclerView.OnFlingListener)}.
  • You can call this method with {@code null} to detach it from the current RecyclerView.

Caution

SnapHelper.attachToRecyclerView() can throw IllegalArgumentException

  • @throws IllegalArgumentException if there is already a {@link RecyclerView.OnFlingListener}
  • attached to the provided {@link RecyclerView}.
like image 31
Rahul Khurana Avatar answered Oct 11 '22 05:10

Rahul Khurana