思路:开启一个子线程,在子线程中设置当前页卡的位置并向主线程中发送消息,每隔一定的时间间隔执行一次子线程,然后用handler接收子线程发过来的消息,并在这里刷新UI(设置当前位置的图片)。
1.使用timer实现
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
currentItem = (currentItem +1) % imageViews.size();
handler.sendEmptyMessage(0);
}
},2000,2000);
handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
viewPager.setCurrentItem(currentItem);
return false;
}
});
2.使用Thread实现:这里在run方法里为了能一直使图片轮播,所以把把要执行的任务放在死循环里
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true){
Thread.sleep(2000);
currentItem = (currentItem + 1) % imageViews.size();
handler.sendEmptyMessage(0);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
viewPager.setCurrentItem(currentItem);
return false;
}
});
3.使用线程池实现:首先在onStrat方法里开启线程池,scheduledExecutorService的scheduleWithFixedDelay方法里的参数是
1.子线程,2.初次执行时间,3.时间间隔,4.时间单位
@Override
protected void onStart() {
super.onStart();
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleWithFixedDelay(new MyRunnable(),2,2, TimeUnit.SECONDS);
// 或者用下面一种,效果是一样的
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleAtFixedRate(new MyRunnable(),2,2,TimeUnit.SECONDS);
}
public class MyRunnable implements Runnable{
@Override
public void run() {
currentItem = (currentItem + 1)%imageViews.size();
handler.sendEmptyMessage(0);
}
}
刷新UI的代码
private Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
viewPager.setCurrentItem(currentItem);
return false;
}
});
网友评论