如何以编程方式禁用RecyclerView的滚动

dan*_*anb 24 android android-recyclerview

我有RecyclerView一个LinearLayoutManager方位HORIZONTAL.其中的每个项目都可以包含交互元素(包括垂直元素ScrollView).是否有一种方法可以轻松RecyclerView忽略用户在RecyclerView不拦截触摸事件给孩子的情况下水平滚动或拖动的任何尝试?

我以编程方式控制其滚动效果,RecyclerView直到用户将其翻转为止.

我尝试了一些非常简单的想法,当我在响应某些事件时调用smoothScrollToPosition时,我启用滚动并禁用触摸事件,直到滚动结束.像这样:

  private class NoScrollHorizontalLayoutManager extends LinearLayoutManager {
    ScrollingTouchInterceptor interceptor = new ScrollingTouchInterceptor();
    protected boolean canScroll;

    public NoScrollHorizontalLayoutManager(Context ctx) {
      super(ctx, LinearLayoutManager.HORIZONTAL, false);
    }

    public RecyclerView.OnItemTouchListener getInterceptor() {
      return interceptor;
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
      canScroll = true;
      super.smoothScrollToPosition(recyclerView, state, position);
    }

    @Override
    public void onScrollStateChanged(int state) {
      super.onScrollStateChanged(state);
      if(state == RecyclerView.SCROLL_STATE_IDLE) {
        canScroll = false;
      }
    }

    @Override
    public boolean canScrollHorizontally() {
      return canScroll;
    }

    public class ScrollingTouchInterceptor implements RecyclerView.OnItemTouchListener {
      @Override
      public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        return canScrollHorizontally();
      }

      @Override
      public void onTouchEvent(RecyclerView rv, MotionEvent e) {
      }

      @Override
      public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

并像这样使用它..

NoScrollHorizontalLayoutManager layout = new NoScrollHorizontalLayoutManager(context);
recycler.setLayoutManager(layout);
recycler.addOnItemTouchListener(layout.getInterceptor());
Run Code Online (Sandbox Code Playgroud)

实际上几乎可以工作......但是当光滑的滚动运动时,我仍然可以通过点击屏幕搞砸程序滚动.很明显,我错过了一些明显的东西,或者有更聪明的方法来做到这一点.

更新了非RecyclerView解决方案在这里找到: 如何通过在ViewPager中用手指滑动禁用分页,但仍然能够以编程方式滑动?

/**
 * ViewPager that doesn't allow swiping.
 */
public class NonSwipeableViewPager extends ViewPager {

  public NonSwipeableViewPager(Context context) {
    super(context);
  }

  public NonSwipeableViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  @Override
  public boolean onInterceptTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return false;
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 -2

android:nestedScrollingEnabled="false"
Run Code Online (Sandbox Code Playgroud)

在 xml 文件中的 RecyclerView TAG 中执行上述操作。


归档时间:

查看次数:

11636 次

最近记录:

6 年 前