How To Implement Timer Into Automatically Image Slide Inside The Fragment?
How to implement timer into Automatically image slide inside the fragment? I used Fragment and CustomSwipeAdapter and I dont know where to put the timer to make the images automat
Solution 1:
Handlerh=newHandler();
intdelay=15000; //1 second
Runnable runnable;
privateint[] pagerIndex = {-1};
@OverridepublicvoidonStart() {
h.postDelayed(newRunnable() {
publicvoidrun() {
pagerIndex[0]++;
if (pagerIndex[0] >= adapter.getCount()) {
pagerIndex[0] = 0;
}
viewPager.setCurrentItem(pagerIndex[0]);
runnable=this;
h.postDelayed(runnable, delay);
}
}
, delay);
super.onStart();
}
Solution 2:
You could start a timed task in you Fragment
.
Haven't verified this code yet, but it should work fine.
Create your swipe task :
finallongdelay=2000;
Handlerhandler=newHandler();
privateint[] pagerIndex = {-1};
privateRunnableswipeTask=newRunnable() {
@Overridepublicvoidrun() {
pagerIndex[0]++;
if (pagerIndex[0] >= adapter.getCount()) {
pagerIndex[0] = 0;
}
viewPager.setCurrentItem(pagerIndex[0]);
handler.postDelayed(this, delay);
}
};
And in your fragment's onCreateView()
, after the viewPager, adapter etc have been set,
task.run();
Solution 3:
privateintcurrentPage=0;
finallongDELAY=1000;//delay in milliseconds before auto sliding starts.finallongPERIOD=4000; //time in milliseconds between sliding.privatevoidautoScroll(){
finalHandlerhandler=newHandler();
finalRunnableUpdate=newRunnable() {
publicvoidrun() {
if (currentPage == YourImageList.size()) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
}
};
timer = newTimer(); // creating a new thread
timer .schedule(newTimerTask() { // task to be scheduled@Overridepublicvoidrun() {
handler.post(Update);
}
}, DELAY_MS, PERIOD_MS);
}
Call autoScroll() in onCreateView() of your fragment, after your view pager adapter is set.
viewPager.setAdapter(ViewPagerAdapter)
autoScroll()
If you have to change between fragments, remember to cancel timer in onDetach() method of your fragment as shown below to avoid any issues.
@OverridepublicvoidonDetach() {
super.onDetach();
if(timer != null) {
timer.cancel();
timer = null;
}
}
Hope this will help someone. Since I personally experienced an issue with sliding when moving to another fragment and coming back to the same fragment since I had not cancel the timer before moving to another fragment.
Post a Comment for "How To Implement Timer Into Automatically Image Slide Inside The Fragment?"