Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/197.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何使用TimeTask自动滑动ViewPager图像_Android - Fatal编程技术网

Android 如何使用TimeTask自动滑动ViewPager图像

Android 如何使用TimeTask自动滑动ViewPager图像,android,Android,大家好,我是android新手,在我的应用程序中,我的ArrayList中有很多图像 为什么我想借助Timetasker每隔3秒自动刷一次这些图像,这个过程需要不断重复,直到我们关闭应用程序。有人能帮帮我吗 主要活动:- 自定义适配器:- 请尝试以下代码: 主要活动- int currentIndex=0; //for tracking current item 根据需要创建并设置TimerTask,然后在TimerTask的run()中: public void run() { i

大家好,我是android新手,在我的应用程序中,我的
ArrayList中有很多图像
为什么我想借助
Timetasker
每隔3秒自动刷一次这些图像,这个过程需要不断重复,直到我们关闭应用程序。有人能帮帮我吗

主要活动:- 自定义适配器:- 请尝试以下代码: 主要活动-

int currentIndex=0; //for tracking current item 
根据需要创建并设置TimerTask,然后在TimerTask的
run()
中:

public void run() {
    if((currentIndex+1)>imageId.length() ){
      currentIndex=0;
    }else{
      currentIndex++;
    }
    ViewPager.setCurrentItem(currentIndex);
}

在活动中创建处理程序,然后计划任务。我认为Handler足以完成这项小任务。不要用定时器

Runnable timeCounter = new Runnable() {

        @Override
        public void run() {
                 if((currentIndex+1)>imageId.length() ){
                      currentIndex=0;
                  }else{
                      currentIndex++;
                 }
                ViewPager.setCurrentItem(currentIndex);
                handler.postDelayed(timeCounter, 3*1000);

        }
    };
handler.postDelayed(timeCounter, 3*1000);
然后在onDestroy()中或您想停止的任何地方

handler.removeCallbacks(timeCounter);

尝试使用ViewFlipper而不是viewpager

布局xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ViewFlipper
    android:id="@+id/imageFrames"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:drawable/screen_background_dark" >
</ViewFlipper>

<Button
    android:id="@+id/slideShowBtn"
    android:layout_width="200dp"
    android:layout_height="wrap_content"


以下是使用
TimerTask
的总代码:

public class MainActivity extends AppCompatActivity {

ViewPager viewPager;

Integer[] imageId = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};
String[] imagesName = {"image1","image2","image3","image4"};

Timer timer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);

    viewPager = (ViewPager) findViewById(R.id.viewPager);
    PagerAdapter adapter = new CustomAdapter(MainActivity.this,imageId,imagesName);
    viewPager.setAdapter(adapter);

    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            viewPager.post(new Runnable(){

                @Override
                public void run() {
                    viewPager.setCurrentItem((viewPager.getCurrentItem()+1)%imageId.length);
                }
            });
        }
    };
    timer = new Timer();
    timer.schedule(timerTask, 3000, 3000);
}

@Override
protected void onDestroy() {
    timer.cancel();
    super.onDestroy();
}
}

您的问题已得到回答

将此添加到MainActivity.java中

//...   
int currentPage = 0;
Timer timer;
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.


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);

    viewPager = (ViewPager) findViewById(R.id.viewPager);
    PagerAdapter adapter = new CustomAdapter(MainActivity.this,imageId,imagesName);
    viewPager.setAdapter(adapter);

    /*After setting the adapter use the timer */
    final Handler handler = new Handler();
    final Runnable Update = new Runnable() {
        public void run() {
            if (currentPage == NUM_PAGES-1) {
                currentPage = 0;
            }
            viewPager.setCurrentItem(currentPage++, 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);
}

以下是自动滚动viewpager项的代码:

public class MainActivity extends AppCompatActivity {

    AutoScrollViewPager viewPager;

    Integer[] imageId = {R.drawable.commitementlogo, R.drawable.like, R.drawable.like_select, R.drawable.plus};
    String[] imagesName = {"image1","image2","image3","image4"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager= (AutoScrollViewPager) findViewById(R.id.viewpager);
        viewPager.startAutoScroll();
        viewPager.setInterval(3000);
        viewPager.setCycle(true);
        viewPager.setStopScrollWhenTouch(true);

        PagerAdapter adapter = new CustomAdapter(MainActivity.this,imageId,imagesName);
        viewPager.setAdapter(adapter);

    }


}
这里是AutoscrollViewpager类:

public class AutoScrollViewPager extends ViewPager {

    public static final int        DEFAULT_INTERVAL            = 1500;

    public static final int        LEFT                        = 0;
    public static final int        RIGHT                       = 1;

    /** do nothing when sliding at the last or first item **/
    public static final int        SLIDE_BORDER_MODE_NONE      = 0;
    /** cycle when sliding at the last or first item **/
    public static final int        SLIDE_BORDER_MODE_CYCLE     = 1;
    /** deliver event to parent when sliding at the last or first item **/
    public static final int        SLIDE_BORDER_MODE_TO_PARENT = 2;

    /** auto scroll time in milliseconds, default is {@link #DEFAULT_INTERVAL} **/
    private long                   interval                    = DEFAULT_INTERVAL;
    /** auto scroll direction, default is {@link #RIGHT} **/
    private int                    direction                   = RIGHT;
    /** whether automatic cycle when auto scroll reaching the last or first item, default is true **/
    private boolean                isCycle                     = true;
    /** whether stop auto scroll when touching, default is true **/
    private boolean                stopScrollWhenTouch         = true;
    /** how to process when sliding at the last or first item, default is {@link #SLIDE_BORDER_MODE_NONE} **/
    private int                    slideBorderMode             = SLIDE_BORDER_MODE_NONE;
    /** whether animating when auto scroll at the last or first item **/
    private boolean                isBorderAnimation           = true;
    /** scroll factor for auto scroll animation, default is 1.0 **/
    private double                 autoScrollFactor            = 1.0;
    /** scroll factor for swipe scroll animation, default is 1.0 **/
    private double                 swipeScrollFactor           = 1.0;

    private Handler handler;
    private boolean                isAutoScroll                = false;
    private boolean                isStopByTouch               = false;
    private float                  touchX                      = 0f, downX = 0f;
    private CustomDurationScroller scroller                    = null;

    public static final int        SCROLL_WHAT                 = 0;

    public AutoScrollViewPager(Context paramContext) {
        super(paramContext);
        init();
    }

    public AutoScrollViewPager(Context paramContext, AttributeSet paramAttributeSet) {
        super(paramContext, paramAttributeSet);
        init();
    }

    private void init() {
        handler = new MyHandler(this);
        setViewPagerScroller();
    }

    /**
     * start auto scroll, first scroll delay time is {@link #getInterval()}
     */
    public void startAutoScroll() {
        isAutoScroll = true;
        sendScrollMessage((long)(interval + scroller.getDuration() / autoScrollFactor * swipeScrollFactor));
    }

    /**
     * start auto scroll
     * 
     * @param delayTimeInMills first scroll delay time
     */
    public void startAutoScroll(int delayTimeInMills) {
        isAutoScroll = true;
        sendScrollMessage(delayTimeInMills);
    }

    /**
     * stop auto scroll
     */
    public void stopAutoScroll() {
        isAutoScroll = false;
        handler.removeMessages(SCROLL_WHAT);
    }

    /**
     * set the factor by which the duration of sliding animation will change while swiping
     */
    public void setSwipeScrollDurationFactor(double scrollFactor) {
        swipeScrollFactor = scrollFactor;
    }

    /**
     * set the factor by which the duration of sliding animation will change while auto scrolling
     */
    public void setAutoScrollDurationFactor(double scrollFactor) {
        autoScrollFactor = scrollFactor;
    }

    private void sendScrollMessage(long delayTimeInMills) {
        /** remove messages before, keeps one message is running at most **/
        handler.removeMessages(SCROLL_WHAT);
        handler.sendEmptyMessageDelayed(SCROLL_WHAT, delayTimeInMills);
    }

    /**
     * set ViewPager scroller to change animation duration when sliding
     */
    private void setViewPagerScroller() {
        try {
            Field scrollerField = ViewPager.class.getDeclaredField("mScroller");
            scrollerField.setAccessible(true);
            Field interpolatorField = ViewPager.class.getDeclaredField("sInterpolator");
            interpolatorField.setAccessible(true);

            scroller = new CustomDurationScroller(getContext(), (Interpolator)interpolatorField.get(null));
            scrollerField.set(this, scroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * scroll only once
     */
    public void scrollOnce() {
        PagerAdapter adapter = getAdapter();
        int currentItem = getCurrentItem();
        int totalCount;
        if (adapter == null || (totalCount = adapter.getCount()) <= 1) {
            return;
        }

        int nextItem = (direction == LEFT) ? --currentItem : ++currentItem;
        if (nextItem < 0) {
            if (isCycle) {
                setCurrentItem(totalCount - 1, isBorderAnimation);
            }
        } else if (nextItem == totalCount) {
            if (isCycle) {
                setCurrentItem(0, isBorderAnimation);
            }
        } else {
            setCurrentItem(nextItem, true);
        }
    }

    /**
     * <ul>
     * if stopScrollWhenTouch is true
     * <li>if event is down, stop auto scroll.</li>
     * <li>if event is up, start auto scroll again.</li>
     * </ul>
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int action = ev.getActionMasked();

        if (stopScrollWhenTouch) {
            if ((action == MotionEvent.ACTION_DOWN) && isAutoScroll) {
                isStopByTouch = true;
                stopAutoScroll();
            } else if (ev.getAction() == MotionEvent.ACTION_UP && isStopByTouch) {
                startAutoScroll();
            }
        }

        if (slideBorderMode == SLIDE_BORDER_MODE_TO_PARENT || slideBorderMode == SLIDE_BORDER_MODE_CYCLE) {
            touchX = ev.getX();
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                downX = touchX;
            }
            int currentItem = getCurrentItem();
            PagerAdapter adapter = getAdapter();
            int pageCount = adapter == null ? 0 : adapter.getCount();
            /**
             * current index is first one and slide to right or current index is last one and slide to left.<br/>
             * if slide border mode is to parent, then requestDisallowInterceptTouchEvent false.<br/>
             * else scroll to last one when current item is first one, scroll to first one when current item is last
             * one.
             */
            if ((currentItem == 0 && downX <= touchX) || (currentItem == pageCount - 1 && downX >= touchX)) {
                if (slideBorderMode == SLIDE_BORDER_MODE_TO_PARENT) {
                    getParent().requestDisallowInterceptTouchEvent(false);
                } else {
                    if (pageCount > 1) {
                        setCurrentItem(pageCount - currentItem - 1, isBorderAnimation);
                    }
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                return super.dispatchTouchEvent(ev);
            }
        }
        getParent().requestDisallowInterceptTouchEvent(true);

        return super.dispatchTouchEvent(ev);
    }

    private static class MyHandler extends Handler {

        private final WeakReference<AutoScrollViewPager> autoScrollViewPager;

        public MyHandler(AutoScrollViewPager autoScrollViewPager) {
            this.autoScrollViewPager = new WeakReference<AutoScrollViewPager>(autoScrollViewPager);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case SCROLL_WHAT:
                    AutoScrollViewPager pager = this.autoScrollViewPager.get();
                    if (pager != null) {
                        pager.scroller.setScrollDurationFactor(pager.autoScrollFactor);
                        pager.scrollOnce();
                        pager.scroller.setScrollDurationFactor(pager.swipeScrollFactor);
                        pager.sendScrollMessage(pager.interval + pager.scroller.getDuration());
                    }
                default:
                    break;
            }
        }
    }

    /**
     * get auto scroll time in milliseconds, default is {@link #DEFAULT_INTERVAL}
     * 
     * @return the interval
     */
    public long getInterval() {
        return interval;
    }

    /**
     * set auto scroll time in milliseconds, default is {@link #DEFAULT_INTERVAL}
     * 
     * @param interval the interval to set
     */
    public void setInterval(long interval) {
        this.interval = interval;
    }

    /**
     * get auto scroll direction
     * 
     * @return {@link #LEFT} or {@link #RIGHT}, default is {@link #RIGHT}
     */
    public int getDirection() {
        return (direction == LEFT) ? LEFT : RIGHT;
    }

    /**
     * set auto scroll direction
     * 
     * @param direction {@link #LEFT} or {@link #RIGHT}, default is {@link #RIGHT}
     */
    public void setDirection(int direction) {
        this.direction = direction;
    }

    /**
     * whether automatic cycle when auto scroll reaching the last or first item, default is true
     * 
     * @return the isCycle
     */
    public boolean isCycle() {
        return isCycle;
    }

    /**
     * set whether automatic cycle when auto scroll reaching the last or first item, default is true
     * 
     * @param isCycle the isCycle to set
     */
    public void setCycle(boolean isCycle) {
        this.isCycle = isCycle;
    }

    /**
     * whether stop auto scroll when touching, default is true
     * 
     * @return the stopScrollWhenTouch
     */
    public boolean isStopScrollWhenTouch() {
        return stopScrollWhenTouch;
    }

    /**
     * set whether stop auto scroll when touching, default is true
     * 
     * @param stopScrollWhenTouch
     */
    public void setStopScrollWhenTouch(boolean stopScrollWhenTouch) {
        this.stopScrollWhenTouch = stopScrollWhenTouch;
    }

    /**
     * get how to process when sliding at the last or first item
     * 
     * @return the slideBorderMode {@link #SLIDE_BORDER_MODE_NONE}, {@link #SLIDE_BORDER_MODE_TO_PARENT},
     *         {@link #SLIDE_BORDER_MODE_CYCLE}, default is {@link #SLIDE_BORDER_MODE_NONE}
     */
    public int getSlideBorderMode() {
        return slideBorderMode;
    }

    /**
     * set how to process when sliding at the last or first item
     * 
     * @param slideBorderMode {@link #SLIDE_BORDER_MODE_NONE}, {@link #SLIDE_BORDER_MODE_TO_PARENT},
     *        {@link #SLIDE_BORDER_MODE_CYCLE}, default is {@link #SLIDE_BORDER_MODE_NONE}
     */
    public void setSlideBorderMode(int slideBorderMode) {
        this.slideBorderMode = slideBorderMode;
    }

    /**
     * whether animating when auto scroll at the last or first item, default is true
     * 
     * @return
     */
    public boolean isBorderAnimation() {
        return isBorderAnimation;
    }

    /**
     * set whether animating when auto scroll at the last or first item, default is true
     * 
     * @param isBorderAnimation
     */
    public void setBorderAnimation(boolean isBorderAnimation) {
        this.isBorderAnimation = isBorderAnimation;
    }
}

并将适配器设置为与之前设置的相同。

答案的另一个版本:-

                    private int currentPage = -1;
                    // start auto scroll of viewpager
                    final Handler handler = new Handler();
                    final Runnable Update = new Runnable() {
                        public void run() {
                            viewPager.setCurrentItem(++currentPage, true);
                            // go to initial page i.e. position 0
                            if (currentPage == NUM_PAGES -1) {
                                currentPage = -1;
                                // ++currentPage will make currentPage = 0
                            }
                        }
                    };

                    timer = new Timer(); // This will create a new Thread
                    timer.schedule(new TimerTask() { // task to be scheduled

                        @Override
                        public void run() {
                            handler.post(Update);
                        }
                    }, 500, 1500);

它每5秒更新一次(5000)

您可以使用安卓
TabLayout
来显示指示器,
ViewPager
来显示滑动屏幕,
TimerTask
来自动滑动

请查看此链接以了解分步指南和演示


要获得自动显示一系列图像的简单解决方案,请尝试xml文件中的ViewFlipper。并非适用于所有目的,但我发现这是一个有用的解决方案,我把一些东西放在一起

 <ViewFlipper
android:id="@+id/viewflipper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoStart="true"
android:flipInterval="2000" >

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture1" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture2" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture3" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture4" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture5" />

在onCreate()方法中尝试此操作


Kotlin中的自动滑动ViewPager,简单易用的代码。(如果只有2页)


对@L.Swifter代码片段的简单编辑对于那些想知道变量的人来说,我将其包装在一个方法中,您可以在设置适配器后将其添加到您的活动中

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

使用
ViewPager.setCurrentItem(索引)要更改查看寻呼机项目,请每3秒清楚阅读我的问题图像需要自动滑动,此过程需要执行到我们关闭应用程序请帮助我使用一些编码CAN u请告诉我如何创建处理程序以及如何调用创建变量的活动。只需复制下面的代码。Handler=newhandler();请随时在评论中询问任何问题此currentPage是什么,NUM_PAGEScurrentPage是您当前所在的页面。NUM_PAGES是总页数。。在您的情况下,您提供的代码不会重置计时器。我的意思是当最后一页出现时,它就停止工作了。它应该一次又一次地运行计时器@R.Kyou忘记在你的方法中使用DELAY和PERIOD,你可以从这里找到演示这个答案对我很有用,但是MotionEventCompat.getActionMasked被拒绝,可能被零除错误在这里`
viewPager.setCurrentItem((viewPager.getCurrentItem()+1)%imageId.length)动态填充imageId数组时。因此我们使用
viewPager.setCurrentItem((viewPager.getCurrentItem()+1)%imageId.length+1)
public class CustomDurationScroller extends Scroller {

    private double scrollFactor = 1;

    public CustomDurationScroller(Context context) {
        super(context);
    }

    public CustomDurationScroller(Context context, Interpolator interpolator) {
        super(context, interpolator);
    }

    public void setScrollDurationFactor(double scrollFactor) {
        this.scrollFactor = scrollFactor;
    }

    @Override
    public void startScroll(int startX, int startY, int dx, int dy, int duration) {
        super.startScroll(startX, startY, dx, dy, (int)(duration * scrollFactor));
    }
}
                    private int currentPage = -1;
                    // start auto scroll of viewpager
                    final Handler handler = new Handler();
                    final Runnable Update = new Runnable() {
                        public void run() {
                            viewPager.setCurrentItem(++currentPage, true);
                            // go to initial page i.e. position 0
                            if (currentPage == NUM_PAGES -1) {
                                currentPage = -1;
                                // ++currentPage will make currentPage = 0
                            }
                        }
                    };

                    timer = new Timer(); // This will create a new Thread
                    timer.schedule(new TimerTask() { // task to be scheduled

                        @Override
                        public void run() {
                            handler.post(Update);
                        }
                    }, 500, 1500);
 int ci=0;
 java.util.Timer timer;
 timer=new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            viewPager.post(new Runnable() {
                @Override
                public void run() {

                    Log.d("viewPager",""+ci);
                    viewPager.setCurrentItem(ci%7);
                    ci++;

                }
            });
        }
    },1000,5000);
 <ViewFlipper
android:id="@+id/viewflipper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoStart="true"
android:flipInterval="2000" >

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture1" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture2" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture3" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture4" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture5" />
    final Handler handler = new Handler();
    Timer timer = new Timer();
    final Runnable runnable = new Runnable() {
        public void run() {
            int currentPage=viewPager.getCurrentItem();
            //return to first page, if current page is last page  
            if (currentPage == titleNames.length-1) {
                currentPage = -1;
            }
            viewPager.setCurrentItem(++currentPage, true);
        }
    };
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            handler.post(runnable);
        }
    },DELAY,PERRIOD)
val handler = Handler()
val update = Runnable {
       viewPager.setCurrentItem(currentPage % 2, true);
       currentPage++
      }
var timer = Timer()// This will create a new Thread
    timer!!.schedule(object : TimerTask() {
         override fun run() {
         handler.post(update)
         }
   }, 500(DELAY_MS), 3000(PERIOD_MS))
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);
}