Android RecyclerView的滑动监听

1 RecyclerView 的滑动监听

1.1 RecyclerView 设置滑动监听


mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

1.2 滑动监听回调方法说明

1.3 判断RecyclerView的滑动方向

  • onScrollStateChanged(RecyclerView recyclerView, int newState)这个方法在RecyclerView的滑动状态改变时会调用

对应的参数 newState 有三种状态 ,官方这样描述

    /**
     * The RecyclerView is not currently scrolling.
     * @see #getScrollState()
     */
    public static final int SCROLL_STATE_IDLE = 0;

    /**
     * The RecyclerView is currently being dragged by outside input such as user touch input.
     * @see #getScrollState()
     */
    public static final int SCROLL_STATE_DRAGGING = 1;

    /**
     * The RecyclerView is currently animating to a final position while not under
     * outside control.
     * @see #getScrollState()
     */
    public static final int SCROLL_STATE_SETTLING = 2;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

也就是说,newState=0时,RecyclerView在停止状态中 
newState=1和newState=2时,RecyclerView在滑动状态中 
不同的是,当由0—>1 ,2 时,RecyclerView由静止状态下变为滑动状态,然后1–0 滑动状态变为静止(调用方法 mHomeDateRecyclerView.smoothScrollToPosition(currentPostion); 等这一类方法所触发) , 2–>0 滑动状态变为静止状态(左右滑动RecyclerView 动态的慢慢结束)

  • onScrolled(RecyclerView recyclerView, int dx, int dy ) 这个方法在RecyclerView开始滑动时实时回调

参数dx dy分别是RecyclerView在滑动过程中,在x轴方向(横向滑动)与Y轴方向(纵向滑动)的偏移量 
dx>0 向右滑动 
dx<0 向左滑动

dy<0 向上滑动 
dy>0 向下滑动

 


2 RecyclerView 的滑动滑动距离获取

可以在RecyclerView的滑动监听中调用此方法,以不断的来获取RecyclerView的滑动距离

//mMTrainLinearLayoutManager 是 Recyclerview对应的布局管理者
if (mMTrainLinearLayoutManager != null) {
       //获取RecyclerView当前顶部显示的第一个条目对应的索引    
       int position = mMTrainLinearLayoutManager.findFirstVisibleItemPosition();
       //根据索引来获取对应的itemView 
       View firstVisiableChildView = mMTrainLinearLayoutManager.findViewByPosition(position);
       //获取当前显示条目的高度
       int itemHeight = firstVisiableChildView.getHeight();
       //获取当前Recyclerview 偏移量
       int flag = (position) * itemHeight - firstVisiableChildView.getTop();

       LogUtils.d("scroll " + dx + "  " + dy + " flag " + flag);
   }

你可能感兴趣的:(Android RecyclerView的滑动监听)