我在 ViewPager2 中找不到 PageChangeListener。?

I can't find PageChangeListener in ViewPager2.?

ViewPager2 PageChangeListener 无法正常工作。?

下面是ViewPager2中OnPageChangeListener的示例代码。

class ViewPager2PageChangeCallback(private val listener: (Int) -> Unit) : ViewPager2.OnPageChangeCallback() {
    override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            when (position) {
               //YOUR CODE
            }
        }
    }

registerOnPageChangeCallback 方法:

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

在Java中可以这样编码:

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