How to switch automatically between viewPager pages

后端 未结 8 1317
难免孤独
难免孤独 2020-11-29 08:41

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 kno

8条回答
  •  悲哀的现实
    2020-11-29 08:58

    Below method is use to switch pages automatically after some time (you can modify time as per your requirement)

     private void timer() {
                    timer = new Timer();
                    timer.scheduleAtFixedRate(new TimerTask() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (currentPage == NUM_PAGES - 1) {
                                        currentPage = 0;
                                    }
                                    view.setCurrentItem(currentPage++, true);
                                }
                            });
                        }
                    }, 500, 5000);
                }
    

    if want to endless scroll in viewpager use infinite scroll viewpager class from below provided link and do minor changes (remove condition) in Runnable interface.

    runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
    
                                        view.setCurrentItem(currentPage++, true);
                                    }
                                });
    

    also,don't forget to cancel timer on Destroy view.

提交回复
热议问题