Recyclerview AddOnScrollListener

Charles Galvez picture Charles Galvez · May 5, 2017 · Viewed 7.3k times · Source

I have implemented addonscrollListener for my recyclerview since I want to
hide my FAB when recyclerview is scrolled as follows :

mRvNearby.addOnScrollListener(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);
                Log.e("DY",""+dy);
                if(dy<0){
                    mFloatingActionMenu.hideMenuButton(true);
                }else{
                    mFloatingActionMenu.showMenuButton(true);
                }
            }
        });

But unfortunately, when I use this listener, the "dy" only changes once, and when I scrolled continuously, the value
hasn't changed.
I was expecting that when scrolled down, The value will be less than 0.
and when scrolled up, the value is greater than 0.

Answer

R.R.M picture R.R.M · May 5, 2017

Use greater than sign instead of less than. When you scroll down the value is greater than 0. So your code will be :

 mRvNearby.addOnScrollListener(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);
            Log.e("DY",""+dy);
            if(dy>0){
                mFloatingActionMenu.hideMenuButton(true);
            }else{
                mFloatingActionMenu.showMenuButton(true);
            }
        }
    });