Search code examples
androidkotlinandroid-viewpagerandroid-viewpager2

ViewPager2 - How to use registerOnPageChangeCallback to check view pager item position


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)
            }
        })

Solution

  • 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)
                }
            })