Android viewpager animation

2019-04-07 20:26发布

I would like to be informed when the animation ends after this function call:

viewPager.setCurrentItem(2, true);

Does anyone know how to accomplish this?

2条回答
再贱就再见
2楼-- · 2019-04-07 20:46

You can use a OnPageChangeListener..

viewPager.setOnPageChangeListener(new OnPageChangeListener() {

    @Override
    public void onPageSelected(int arg0) {
        // The code you want to run when scrolling is complete              
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {}

    @Override
    public void onPageScrollStateChanged(int arg0) {}
});

When a new page is selected, onPageSelected() gets called.

查看更多
甜甜的少女心
3楼-- · 2019-04-07 20:53

I have come across the same issue. the following is my conclusion:

When the page is actually changed onPageSelected will be called. But it's called before the animation.

When the animation stopped , onPageScrollStateChanged will be called with state SCROLL_STATE_IDLE.

So you have to combine this two function calls to get your function called.

Good Luck.

private class PageChangeListener implements OnPageChangeListener {

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
   }

    @Override
    public void onPageSelected(int position) {
        isPageChanged = true;
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        switch (state) {
        case ViewPager.SCROLL_STATE_IDLE:
            if (isPageChanged) {
                updateCurrentPage();//this will be called when animation ends
                isPageChanged = false;
            }
            break;
        case ViewPager.SCROLL_STATE_DRAGGING:
            break;
        case ViewPager.SCROLL_STATE_SETTLING:
            break;
        }
    }
}
查看更多
登录 后发表回答