Reputation: 2437
I want to implement an image slider with viewpager. The slider should automatically scroll horizontally. So I use a timer as below:
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES-1) {
currentPage = 0;
timer.cancel();
timer = new Timer();
}
mPager.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);
}
}, 500, 3000);
mPager
is the viewpager which already has been set.
The problem is that when it reaches the last item (image), it stops there and doesn't scroll anymore. Another thing, when I scroll it manually to the first page, it suddenly scrolls to the last page ignorant of timer.
Any help would be appreciated.
Upvotes: 1
Views: 506
Reputation: 11642
You can try this,
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
int currentPage = mPager.getCurrentItem();
if (currentPage == NUM_PAGES-1) {
currentPage = 0;
} else {
currentPage++;
}
mPager.setCurrentItem(currentPage, true);
handler.postDelayed(this, 5000);
}
};
handler.postDelayed(Update, 500);
Upvotes: 2