Android Studio 我在ViewPager2中找不到页面更改侦听器,

vyu0f0g1  于 2022-11-16  发布在  Android
关注(0)|答案(4)|浏览(115)

ViewPager2 PageChangeListener得工作方式与普通ViewPager不同.“

ruyhziif

ruyhziif1#

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

brc7rcf02#

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

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

eqqqjvef3#

在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));
    }
});
1hdlvixo

1hdlvixo4#

你可以这样做。

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

相关问题