androidandroid-viewpageruiviewanimation

How to switch automatically between viewPager pages


I have an android application that employs a ViewPager with two pages When the activity first displays i would like to present each page in turn to the user so that they know they can swipe between to two views. I have failed to find any docs describing how to do this. I have discovered PageTransformations which sounded promising but the user has to swipe first. I need my two pages to scroll automatically as soon as the first page in the ViewPager displays. how can a achieve the desired result?


Solution

  • 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...