Search code examples
javaandroidandroid-recyclerviewonscrolllistener

RecyclerView scrolled UP/DOWN listener


How do we know if user scrolled down or up in RecyclerView ?

I tried with RecyclerView#OnScrollListener , it gives the amount of vertical scroll and the scroll state. How do we get the last scroll position when started to dragging and scrolled position when scroll state idle.


Solution

  • Try this way:

    private static int firstVisibleInListview;
    
    firstVisibleInListview = yourLayoutManager.findFirstVisibleItemPosition();
    

    In your scroll listener:

    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;
    
    }