Android RecyclerView 监听滑动

作者: cnbzlj 发布时间: 2019-09-19 浏览: 4233 次 编辑

今天,简单讲讲Android 如何监听滑动。

不废话了,主要是需要做一个功能,实现RecyclerView滑动时,让一个标题栏固定显示在顶部。

1,基本知识:

列表的滚动一般分为两种:

手指按下 -> 手指拖拽列表移动 -> 手指停止拖拽 -> 抬起手指

手指按下 -> 手指快速拖拽后抬起手指 -> 列表继续滚动 -> 停止滚动

从上面可以看出,滚动状态分为:

|--静止
|--滚动
    |--被迫拖拽移动
    |--自己滚动

上面的过程的状态变化如下:

静止 -> 被迫拖拽移动 -> 静止

静止 -> 被迫拖拽移动 -> 自己滚动 -> 静止

<!--more-->

2,监听RecyclerView的滚动

好了,我们分析完滚动的过程,再看看如何监听RecyclerView的滚动.查看源码是最好的方法.

3,看源码

查看RecyclerView的源码,我们可以看到以下代码:

public abstract static class OnScrollListener {
    /**
     * Callback method to be invoked when RecyclerView's scroll state changes.
     * @param recyclerView The RecyclerView whose scroll state has changed.
     * @param newState     The updated scroll state. One of {@link #SCROLL_STATE_IDLE},
     *                     {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING}.
     */
    public void onScrollStateChanged(RecyclerView recyclerView, int newState){}
 
    /**
     * Callback method to be invoked when the RecyclerView has been scrolled. This will be
     * called after the scroll has completed.
     * <p>
     * This callback will also be called if visible item range changes after a layout
     * calculation. In that case, dx and dy will be 0.
     *
     * @param recyclerView The RecyclerView which scrolled.
     * @param dx The amount of horizontal scroll.
     * @param dy The amount of vertical scroll.
     */
    public void onScrolled(RecyclerView recyclerView, int dx, int dy){}
}

在滚动过程中,此监听器会回调两个方法.

onScrollStateChanged : 滚动状态变化时回调
onScrolled : 滚动时回调

这两者的区别在于: 状态与过程

4,举例子

demoRv = (RecyclerView) findViewById(R.id.demo_rv);
layoutManager = new LinearLayoutManager(this);
demoRv.setLayoutManager(layoutManager);
demoRv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
 
bookAdapter = new BookAdapter();
bookAdapter.fillList(MockService.getBookList());
demoRv.setAdapter(bookAdapter);
 
demoRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        Log.i(TAG, "-----------onScrollStateChanged-----------");
        Log.i(TAG, "newState: " + newState);
    }
 
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        Log.i(TAG, "-----------onScrolled-----------");
        Log.i(TAG, "dx: " + dx);
        Log.i(TAG, "dy: " + dy);
        Log.i(TAG, "CHECK_SCROLL_UP: " + recyclerView.canScrollVertically(TAG_CHECK_SCROLL_UP));
        Log.i(TAG, "CHECK_SCROLL_DOWN: " + recyclerView.canScrollVertically(TAG_CHECK_SCROLL_DOWN));
    }
});