Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't find PageChangeListener in ViewPager2.?

ViewPager2 PageChangeListener is not working like normal ViewPager.?

like image 869
Unaisul Hadi Avatar asked Jan 22 '20 06:01

Unaisul Hadi


People also ask

How do I import ViewPager2?

Go to app > Gradle Scripts > build. gradle (Module: app) and then write the following dependency ” implementation 'androidx. viewpager2:viewpager2:1.0. 0' ” into dependencies section as shown below and then click on Sync now.

How do I turn off ViewPager2 swipe?

You can easily do that by creating a custom class inherits from viewPager and override two methods: “onTouchEvent()” and “onInterceptTouchEvent()” and return true or false to disable and enable the swiping on certain touch events i.e say swiping.


2 Answers

There is registerOnPageChangeCallback method for that:

pager.registerOnPageChangeCallback(object: ViewPager2.OnPageChangeCallback() {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
            }

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
            }

            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)
            }
        })
like image 89
Pavlo Zoria Avatar answered Oct 16 '22 01:10

Pavlo Zoria


Below is the sample code for OnPageChangeListener in ViewPager2.

class ViewPager2PageChangeCallback(private val listener: (Int) -> Unit) : ViewPager2.OnPageChangeCallback() {
    override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            when (position) {
               //YOUR CODE
            }
        }
    }
like image 7
Vir Rajpurohit Avatar answered Oct 16 '22 01:10

Vir Rajpurohit