Android ViewPager automatically change page

僤鯓⒐⒋嵵緔 提交于 2019-11-27 18:34:44
Md Abdul Gafur

If you want to use thread in main ui then you need to use hander to hand it.

Handler handler = new Handler();

        Runnable update = new Runnable() {
            public void run() {
                if (currentPage == NUM_PAGES - 1) {
                    currentPage = 0;
                }
                featureViewPager.setCurrentItem(currentPage++, true);
            }
        };


        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {
                handler.post(update);
            }
        }, 100, 500);

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 );

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!