Non stop auto scroll of viewpager in android
I have used timer to auto swipe the viewpager. But after reaching the last page the timer stops. How to make it to continue again from the first page?
final Handler mHandler = new Handler();
final Runnable mUpdateResults = new Runnable() {
public void run() {
pager.setCurrentItem(page++);
}
};
int delay = 1000; // delay for 1 sec.
int period = 4000; // repeat every 4 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
Solution 1:
final Runnable mUpdateResults = new Runnable() {
public void run() {
int numPages = pager.getAdapter().getCount();
page = (page + 1) % numPages;
pager.setCurrentItem(page);
}
};
That will set the current item to 0 when it exceeds the pager limits
Solution 2:
Latest answer 2021 After you set your viewPager adapter
private Runnable runnable = null;
public void function DisplaySlider(){
sliderItemAdapter = new SliderItemAdapter(getActivity(), mSliderList);//push the data to the adapter
mViewPager.setAdapter(sliderItemAdapter); //set the adapter to the view pager
startAutoSlider(sliderItem.getCount());
}
private void startAutoSlider(final int count) {
runnable = new Runnable() {
@Override
public void run() {
int pos = mViewPager.getCurrentItem();
pos = pos + 1;
if (pos >= count) pos = 0;
mViewPager.setCurrentItem(pos);
handler.postDelayed(runnable, 3000);
}
};
handler.postDelayed(runnable, 3000);
}
And finally don`t forget to free the memory from the callbacks
@Override
public void onDestroy() {
if (runnable != null) handler.removeCallbacks(runnable);
super.onDestroy();
}