Android ViewPager - adding slideshow with fade-in/out animation to switch between views

cubesoft picture cubesoft · May 14, 2012 · Viewed 7.4k times · Source

I use ViewPager to implement my own image gallery. The views consists of ImageViews. The user can normally navigate between images using gestures (as in ViewPager).

What I want to add is the slideshow feature. When user chooses an option "slideshow" from the menu I want to be able to start the animation of ViewPager items - ideally the animation would be the fade-in/out effect between images/slides.

Is it possible to implement this with ViewPager?

Answer

inky picture inky · Aug 9, 2012

Here's how I did it. First I used a lot of the code from the Android Displaying Bitmaps in Your UI tutorial.

Then, I added the following tweaks:

In the OnCreate of the activity that contains the ViewPager:

mPager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {

            PhotoViewerFragment currentFragment = mAdapter
                    .getFragment(arg0);
            if (currentFragment != null) {

                if (mRunningSlideshow) {
                    currentFragment.addImageTransition();
                }

            }

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub
        }

    });

Runnable that runs slideshow in the activity that contains the ViewPager:

   private Runnable runSlideshow = new Runnable() {
        public void run() {
            // Second parameter of false turns ViewPager scroll animation off
            mPager.setCurrentItem(mPager.getCurrentItem() + 1, false);
            mSlideshowHandler.postDelayed(runSlideshow,
                SLIDESHOW_IMAGE_DURATION);
    }
};

In the fragment that displays the image:

private static final int FADE_IN_TIME = 200;

/**
 * Adds fade-in transition when in slideshow mode. Called from PhotoViewerActivity.
 */
public void addImageTransition() {
    // Transition drawable with a transparent drawable and the final bitmap
    final TransitionDrawable td = new TransitionDrawable(new Drawable[] {
            new ColorDrawable(android.R.color.transparent),
            mImageView.getDrawable() });

    mImageView.setImageDrawable(td);
    td.startTransition(FADE_IN_TIME);
}