Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sync scrolling of multiple RecyclerViews

I have a ViewPager showing a fragment per page. This fragment holds a list of items inside a RecyclerView. The list of items is always the same size and the views for the items are also of the same height. When scrolling one of the RecyclerViews, I want the other RecyclerViews to scroll at the same time and the same distance. How would I synchronise the scrolling of the RecyclerViews?

like image 392
gerokeller Avatar asked Jun 08 '15 06:06

gerokeller


1 Answers

Here was my solution. The less the code the better...

lvDetail & lvDetail2 are the RecyclerViews you want to keep in sync.

    final RecyclerView.OnScrollListener[] scrollListeners = new RecyclerView.OnScrollListener[2];
    scrollListeners[0] = new RecyclerView.OnScrollListener( )
    {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            super.onScrolled(recyclerView, dx, dy);
            lvDetail2.removeOnScrollListener(scrollListeners[1]);
            lvDetail2.scrollBy(dx, dy);
            lvDetail2.addOnScrollListener(scrollListeners[1]);
        }
    };
    scrollListeners[1] = new RecyclerView.OnScrollListener( )
    {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            super.onScrolled(recyclerView, dx, dy);
            lvDetail.removeOnScrollListener(scrollListeners[0]);
            lvDetail.scrollBy(dx, dy);
            lvDetail.addOnScrollListener(scrollListeners[0]);
        }
    };
    lvDetail.addOnScrollListener(scrollListeners[0]);
    lvDetail2.addOnScrollListener(scrollListeners[1]);
like image 77
Aace Avatar answered Sep 17 '22 14:09

Aace