Android ViewPager automatically change page

后端 未结 3 1437
广开言路
广开言路 2020-12-04 20:26


I want to schedule an action to change automatically my ViewPager pages. I\'ve tried:

@Override
    public void onCreate(Bundle savedInstanceState) {
           


        
相关标签:
3条回答
  • 2020-12-04 20:30

    If you want to use thread in the main UI then you need to use a hander to hand it.

    Handler handler = new Handler();
    
            Runnable update = new Runnable()  {
    
                public void run() {
                    if ( currentPage == NUM_PAGES ) {
    
                        currentPage = 0;
                    }
                    featureViewPager.setCurrentItem(currentPage++, true);
                }
            };
    
    
            new Timer().schedule(new TimerTask() {
    
                @Override
                public void run() {
                    handler.post(update);
                }
            }, 100, 500);
    
    0 讨论(0)
  • 2020-12-04 20:42

    The TimerTask will runs on it's own thread ( = not the UI thread).

    You can simply call setCurrentItem directly on the main thread using a Handler.

    0 讨论(0)
  • 2020-12-04 20:52

    Easiest way how to solve it is to create an postDelayed runnable

        private Handler mHandler;
        public static final int DELAY = 5000;
    
        Runnable mRunnable = new Runnable()
        {
    
            @Override
            public void run()
            {
                //TODO: do something like mViewPager.setCurrentPage(mIterator);
                mHandler.postDelayed( mRunnable , DELAY );
            }
        };
    

    as You can see it will loop infinitelly. When you want to stop it, just simply call

            mHandler.removeCallbacks( mRunnable );
    
    0 讨论(0)
提交回复
热议问题