Search code examples
androidandroid-viewpager2

How can I make the code take action when swiping to page x on ViewPager2 in Android?


I'm using androidx.viewpager2.widget.ViewPager2.

When user swipes to last page, I want the application to run some code.

I want ViewPager2 to run some code when user swipes to last page (locking the swipe and some other code).

How can I make this happen? What method on ViewPager2 should I use?


Solution

  • Try this:

    binding.viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
                
            if (position == x) {    //you last page index 
                //do what ever you want
            }
        }
    })