How to switch automatically between viewPager pages

You can use Timer for this purpose. The following code is self explanatory:

// ---------------------------------------------------------------------------

Timer timer;
int page = 1;

public void pageSwitcher(int seconds) {
    timer = new Timer(); // At this line a new Thread will be created
    timer.scheduleAtFixedRate(new RemindTask(), 0, seconds * 1000); // delay
                                                                    // in
    // milliseconds
}

    // this is an inner class...
class RemindTask extends TimerTask {

    @Override
    public void run() {

        // As the TimerTask run on a seprate thread from UI thread we have
        // to call runOnUiThread to do work on UI thread.
        runOnUiThread(new Runnable() {
            public void run() {

                if (page > 4) { // In my case the number of pages are 5
                    timer.cancel();
                    // Showing a toast for just testing purpose
                    Toast.makeText(getApplicationContext(), "Timer stoped",
                            Toast.LENGTH_LONG).show();
                } else {
                    mViewPager.setCurrentItem(page++);
                }
            }
        });

    }
}

// ---------------------------------------------------------------------------

Note 1: Make sure that you call pageSwitcher method after setting up adapter to the viewPager properly inside onCreate method of your activity.

Note 2: The viewPager will swipe every time you launch it. You have to handle it so that it swipes through all pages only once (when the user is viewing the viewPager first time)

Note 3: If you further want to slow the scrolling speed of the viewPager, you can follow this answer on StackOverflow.


Tell me in the comments if that could not help you…

Leave a Comment