I can't find PageChangeListener in ViewPager2.?
Asked Answered
G

4

18

ViewPager2 PageChangeListener is not working like normal ViewPager.?

Garland answered 22/1, 2020 at 6:28 Comment(2)
ViewPager2 provides OnPageChangeCallback.Columniation
Thats workingThanksGarland
H
46

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)
            }
        })
Handful answered 5/3, 2021 at 10:10 Comment(1)
just 5 cents from my side: don't forget to unregister the listenerPons
C
7

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
            }
        }
    }
Columniation answered 22/1, 2020 at 6:36 Comment(0)
U
4

In Java one can code it like this:

mViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
    @Override
    public void onPageScrolled(int position,
            float positionOffset, int positionOffsetPixels) {
        super.onPageScrolled(position, positionOffset, positionOffsetPixels);

        setProgress((position + positionOffset) / (mPageCount - 1));
    }
});
Unprofessional answered 15/9, 2021 at 10:19 Comment(0)
Z
1

You can do like this.

viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            super.onPageScrolled(position, positionOffset, positionOffsetPixels);
        }

        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            super.onPageScrollStateChanged(state);
        }
    });
Zephyrus answered 10/11, 2022 at 4:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.