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?
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With