RecyclerView as ViewPager with indicators based on ItemDecoration

Dmitry Chernozubov
Effective Developers
2 min readAug 12, 2019

ViewPager implementation is one of the most trivial features in Android. There is a standard tool to create a pager — ViewPager widget. But to implement indicators you have to use 3rd-party solutions or to write your own custom one. Sometimes there are some limits to use ViewPager (resources, performance, customization etc) and its better to use RecycleView and PageSnapHelper. RecyclerView has the following advantages:
1. It is one of the most popular tools in a developer fork;
2. It is easier and quicker to create an adapter;
3. It works better with memory and resources;
4. It is quicker and more convenient to implement indicators for ViewPage — no more tons of code, no 3rd-party custom views.

RecyclerView and PagerSnapHelper

The duet — RecyclerView and PagerSnapHelper — works great!

Indicators and ItemDecoration

Voila! We have ViewPager, working fantastically, but, most definitely, we have to add indicators to show the amount of the slides and the active slide. We can use ItemDecoration not only to draw the dividers between the list elements, but also for drawing anything we want over RecyclerView with overriding onDrawOver method.

Touch listener

Now we want to move between the elements regardless the active slide. You can suggest your own solution, but I am using RecyclerView.OnItemTouchListener.

Adding two more methods to PagerDecorator: the first one is to define if a point belongs to a circle and the second one is a public function of PagerDecorator class which gets the tap coordinates.

Conclusion

Thanks to this approach, it is easy and convenient to create a pager, having the RecyclerView advantages. Let’s see the bigger picture of what we’ve got: no more tons of code, no more performance loss while having a lot of complex elements, an opportunity to stylize the indicators without using 3rd-party solutions. Pros: ItemDecoration class has few methods for overriding, better performance and is easy to use. Cons: ItemDecoration does not have necessary flexibility by default, and for non-trivial cases you have to come up with custom solutions. Go ahead and play with it: add animation, calculation of the elements count or create the indicators with different forms. Among other things, PageDecorator class is pretty easy to reuse.

--

--