How to swipe ViewPager images automatically using TimeTask

后端 未结 13 2254
天涯浪人
天涯浪人 2020-12-25 13:54

Hi I am new in android and in my app I have a lot of images in my ArrayList that \'s why I want to swipe those images automatically for every 3 seconds with he

13条回答
  •  抹茶落季
    2020-12-25 14:44

    a simple edit to @L. Swifter's code snippet for the ones wondering about variables, I wrapped it all in a method which you can add to your activity after setting the adapter

    private void automateViewPagerSwiping() {
        final long DELAY_MS = 500;//delay in milliseconds before task is to be executed
        final long PERIOD_MS = 3000; // time in milliseconds between successive task executions.
        final Handler handler = new Handler();
        final Runnable update = new Runnable() {
            public void run() {
                if (viewPager.getCurrentItem() == adapter.getCount() - 1) { //adapter is your custom ViewPager's adapter
                    viewPager.setCurrentItem(0);
                }
                else {
                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
                }
            }
        };
    
        timer = new Timer(); // This will create a new Thread
        timer.schedule(new TimerTask() { // task to be scheduled
            @Override
            public void run() {
                handler.post(update);
            }
        }, DELAY_MS, PERIOD_MS);
    }
    

提交回复
热议问题