Search code examples
androidandroid-recyclerviewscrollandroid-viewpagerandroid-tablayout

Auto tab item change on scrolled to bottom in recycler view using Android ViewPager2


I am creating a Calandar-like application. It includes tab layout and fragments beneath the tabs. Tab items in tab layout denote days - "Day 1", "Day 2", "Day 3" etc.

In a fragment beneath the tabs there is recycler view with hours and events that happen at specific hours.

Imagine that user has event that starts at 11:30PM (23:30) Day 1 and finishes at 00:30AM (00:30) Day 2.

I want to implement the feature, that when user scrolls down to 11:59 in Day 1 fragment, the fragment in ViewPager changes automatically to Day 2 fragment (to show the rest of upcoming event).

Is it possible using ViewPager2 in Android or should I look for a different solution?

To detect wheather I reached the bottom I will use solution described in the article bellow: https://medium.com/@ayhamorfali/android-detect-when-the-recyclerview-reaches-the-bottom-43f810430e1e


Solution

  • Once you have detected reached the bottom do get the current page and then set the current page + 1

    ViewPager2.setCurrentItem(ViewPager2.getCurrentItem + 1)

    https://developer.android.com/reference/androidx/viewpager2/widget/ViewPager2#getCurrentItem()

    and

    https://developer.android.com/reference/androidx/viewpager2/widget/ViewPager2#setCurrentItem(int)