Implementing an auto scrolling circular RecyclerView with Kotlin and RxJava

Tomoaki Imai
Aug 27, 2017 · 2 min read
Circular RecyclerView with auto scrolling

I had a situation where I need to implement a circular RecyclerView which loop back to the beginning. Additionally, there was a requirement to auto scroll the view when user is not dragging. There was some useful answers on StackOverFlow, but those were slightly different from what I wanted: it should be swipeable back and forth, and the auto scroll should be controlled by user interaction. So I decided to come up with a better way of doing it using Kotlin and RxJava.

Circular RecyclerView

A basic idea behind a circular RecyclerView is to looping back to the same item in a different element of an array. The diagram below explains how.
Let’s say there are 3 items(item1, item2, item3) in our array. We will add the same items in the first and last. RecyclerView should always start from array[3]. When a visible item reaches array[6] which has item1 inside, we will replace the visible item with array[3]. The same for the backward scrolling.

We can use findFirstVisibleItemPosition to check item visibility. scrollToPosition is used to loop back seemlessly.
Here is the code for InfiniteRotationView and InfiniteRotationAdapter:

Notice that getItemCount() returns list.size * 3.

Now you might recognize this logic consumes 3 times more memory than normal RecyclerView. Since the array only need the first and last elements of its content, the logic can be more efficient by appending the first element to the end of the array and adding the last element to the front of the array. Fortunately The logic becomes slightly simple.

Auto Scrolling

To make RecyclerView auto scroll, we have to call smoothScrollToPosition every specified interval of time. We can use Flowable.interval to emit sequential Long value.

To stop auto scroll if a user swipes RecyclerView, we can listen to the scroll state change.

To stop auto scroll if a user swipes RecyclerView, we can listen to the scroll state change.

Wrap up

All the code is in this repository. Please star if you like it!

)

Tomoaki Imai

Written by

Android Developer at Mercari. Follow me on https://twitter.com/tomoaki_imai (Japanese) https://github.com/tomoima525

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade