ViewPager2 for image slider with thumbnail indicator

Teo
2 min readMay 2, 2021

--

Simple demo to showcase thumbnail indicator with viewpager2 without using any external library

Before switching to ViewPager2, I was ViewPager’s fan due to ViewPager simplicity and many resources of implementation. However, it is time to move on and embrace the new technology. Let’s dive deep into ViewPager2! 😍

After hours of researching for thumbnail indicator for ViewPager2, I got nothing but only basic dot indicator. Hence, I decide to do it from scratch without relying to any 3rd party library.

Before We Start:

We can treat thumbnail indicator as a independent RecyclerView and Image Slider as ViewPager2. But how can we sync between these 2 different component?

Let’s write some code! 👷

First, we create a ImageAdapter to show all the images for the ViewPager2. One of main updated features for ViewPager2 is that, PagerAdapter is now switch to RecyclerView.Adapter. You can read more from here. In here, we use Coil as our image loading library.

Then, we create another ThumbnailAdapter to display all the thumbnail. In here, we create a onThumbnailClick to handle onclick action for thumbnail indicator.

Finally, in our MainActivity, we load bunch of imageUrl from Lorem Ipsum and pass the same dataset into both ImageAdapter and ThumbnailAdapter

There are 2 important concept:

  • For ViewPager2, setup registerOnPageChangeCallback to listen the changes of ViewPager2 and notify the thumbnail indicator.
  • For RecyclerView, handle its onclick by setting ViewPager2’s currentItem.

Cheer 🍷, now Image Slider with its thumbnail indicator is done! 🙌.
You can get the full source-code here: https://github.com/WenLonG12345/ViewPager2-ThumbIndicator

Further Enhancement

Such a media slider is not enough if we only have Images. We have to cater with Video, as well as media with different format. All of these will be enhance in Part II as video playback is quite hard to be controlled and required more researches.

Thanks for reading my 1st Medium article, and hope you gain some knowledge from here 😃

--

--

Teo
Teo

Written by Teo

React & Android Dev, JS & Kotlin Lover, Looking to do more and change the world! 🚀

No responses yet