9

How can I use ViewPager2's registerOnPageChangeCallback facility to check the position of the currently visible ViewPAger2 fragment? I know this will consists of an if/when statement but don't know the correct way to implememnt this.

mViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                if (mViewPager.currentPage) == 0 {
                // do something
                }
                else if (mViewPager.currentPage) == 1 {
                // do something
                }
                else {
                // do something
                }
                super.onPageSelected(position)
            }
        })

2 Answers 2

25

Use the passed position to know where you are:

 mViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                if (position == 0) {
                // you are on the first page
                }
                else if (position == 1) {
                // you are on the second page
                }
                else if (position == 2){
                // you are on the third page
                }
                super.onPageSelected(position)
            }
        })
5

Do not forget to unregister your callback in onDestroy in order to avoid possible memory leaks.

override fun onDestroy() {
    super.onDestroy()
    mViewPager.unregisterOnPageChangeCallback(this)
}
2
  • Could have just updated the accepted answer, also you must pass the callback into ViewPager2.unregisteronpagechangecallback
    – lasec0203
    Aug 9, 2021 at 6:59
  • 3
    Why? After onDestroy the Activity that holds the ViewPager2 is garbage collected anyway --> ViewPager is also garbage collected --> so is the callback
    – Sơn Phan
    Apr 26, 2023 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.