回收器查看滚动的向上/向下侦听器

我们如何知道用户是在 中向下滚动还是向上滚动?RecyclerView

我尝试了 ,它给出了垂直滚动的数量和滚动状态。我们如何在开始拖动时获得最后一个滚动位置,并在滚动状态空闲时获得滚动位置。RecyclerView#OnScrollListener


答案 1

接受的答案工作正常,但@MaciejPigulski在下面的评论中给出了更清晰,更整洁的解决方案。我只是把它放在这里作为一个答案。这是我的工作代码。

mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        if (dy > 0) {
            // Scrolling up
        } else {
            // Scrolling down
        }
    }

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);

        if (newState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
            // Do something
        } else if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
            // Do something
        } else {
            // Do something
        }
    }
});

答案 2

试试这个方法:

private static int firstVisibleInListview;

firstVisibleInListview = yourLayoutManager.findFirstVisibleItemPosition();

在滚动侦听器中:

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

    int currentFirstVisible = yourLayoutManager.findFirstVisibleItemPosition();

    if(currentFirstVisible > firstVisibleInListview)
       Log.i("RecyclerView scrolled: ", "scroll up!");
    else
       Log.i("RecyclerView scrolled: ", "scroll down!");  

    firstVisibleInListview = currentFirstVisible;

}

推荐