How to sync any number of RecyclerViews in a layout

Updated 29 March 2019

Save

If you are in a situation in which you are required to sync your ‘n’ number of Recyclerviews in a layout then we will be discussing how you can achieve this. I have searched for this issue over the internet and there are some solutions too but I found them a little complicated and most of them don’t work properly or work for 2 RecyclerView only. So with the help of those solutions and some modifications, I have developed a way to sync all the RecyclerView in the layout with an easy and clearly understandable logic.

Suppose you have three RecyclerViews in your layout (They can be dynamically or programmatically created) as shown in the example.xml file below.

 

Now, We will be adding a scroll listener and a tag on each of them. The scroll listener will scroll all the other RecyclerView whenever a particular RecyclerView is scrolled.

But there is an issue with this. Whenever a RecyclerView is scrolled, it will scroll all other RecyclerView and then the scroll listener of the other RecyclerView will also do the same and it will become an infinite loop.

To avoid this problem we need to apply a touch listener on each of the RecyclerView which will provide us the information about the RecyclerView which is being scrolled. The for loop actually goes through all the RecyclerViews and scroll each of them one by one except itself.  You can also notice in the above scroll listener the code inside the onScrolled functions in executed only when the tag of that RecyclerView is same as that of the RecyclerView scrolled and the instance variable mTouchedRvTag is initialized inside the touch listener of the RecyclerView.

In the above code segment, we have just changed the value of mTouchedRvTag on the touch event of the RecyclerView. We have returned false this means that the touch Event is not handled inside the interceptor and the onClickListener of the RecyclerView Items will be executed.

That’s all, by using these two listeners you can achieve the syncing of the RecyclerViews. I have tested this logic for 8 – 10  RecyclerViews and it worked fine. You can definitely try for more than that.

Thank you very much. This is Vedesh Kumar signing off.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


8 comments

  • B Todd Poole
    • Vedesh Kumar (Moderator)
  • Rajesh Gauswami
    • Vedesh Kumar (Moderator)
  • Eldho
    • Vedesh Kumar (Moderator)
  • Azhar
  • Pitam Poudel
  • Start a Project


      Message Sent!

      If you have more details or questions, you can reply to the received confirmation email.

      Back to Home