简体   繁体   中英

How to Slide pages automatically in ViewPager Android

I have 4 images in ViewPager and I want to slide all these images one by one And after 4th images, I want to show the 1st image.following code shows the automatic slide page,but stop after 4th image.

            switchtimer= new Timer();
            switchtimer.schedule(new TimerTask() {

                @Override
                public void run() {
                    Log.v("TimerMtd", "Timer call");
                    handler.post(Update);
                }
            }, 1500,3000);
        }
    Handler handler = new Handler();

    Runnable Update = new Runnable() {
        public void run() {
            mPager.setCurrentItem(currentpage);
            currentpage++;
            if(currentpage > 2){
                currentpage = 0;
                Log.v("TimerMtd", currentpage+"cutrrentpage =");
             }

            }
    };

I have made some methods to do the same, got refrence from one of the SO answer but not remembering that right now, below is the code i am using :

Timer timer;
int page = 0;

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 > 5) { // In my case the number of pages are 5
                    page = 0;
                } else {
                    viewPager.setCurrentItem(page);
                    page++;
                }
            }
        });

    }
}

and in onCreate() i call this method like this

 pageSwitcher(3); // Here "3" is delay in seconds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM