如何从 RecyclerView 中删除 SnapHelper

How to remove SnapHelper from a RecyclerView

我使用 attachToRecyclerView(RecyclerView),它按预期工作。

问题:有时候我想让同一个recyclerView正常滚动,如何实现?

代码:

PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
pagerSnapHelper.attachToRecyclerView(recyclerView);

recyclerview-v7:25.1.0开始,足以调用

snapHelper.attachToRecyclerView(null); 

删除 SnapHelper

我遇到了同样的问题。呼叫

clearOnScrollListeners();
setOnFlingListener(null);

RecyclerView 实例上对我有用。在我的情况下,仅调用 setOnFlingListener(null); 是不够的

好吧,它写在 SnapHelper 官方 API:Public 方法上=>attachToRecyclerView:[你想添加这个助手的 RecyclerView 实例 如果你想从当前 RecyclerView.] https://developer.android.com/reference/android/support/v7/widget/SnapHelper.html#attachToRecyclerView%28android.support.v7.widget.RecyclerView%29

如果您不想保留 SnapHelper 的引用,那么根据官方文档还有另一种解决方法,您可以使用

recyclerView.setOnFlingListener(null);

来自 Android 文档

  • 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.

注意

SnapHelper.attachToRecyclerView() 可以抛出 IllegalArgumentException

  • @throws IllegalArgumentException if there is already a {@link RecyclerView.OnFlingListener}
  • attached to the provided {@link RecyclerView}.