Android viewpager animation

2019-04-07 20:19发布

问题:

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?

回答1:

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


回答2:

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.