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:
Handler h = new Handler();
int delay = 15000; //1 second
Runnable runnable;
private int[] pagerIndex = {-1};
@Override
public void onStart() {
h.postDelayed(new Runnable() {
public void run() {
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 :
final long delay = 2000;
Handler handler = new Handler();
private int[] pagerIndex = {-1};
private Runnable swipeTask = new Runnable() {
@Override
public void run() {
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:
private int currentPage = 0;
final long DELAY = 1000;//delay in milliseconds before auto sliding starts.
final long PERIOD = 4000; //time in milliseconds between sliding.
private void autoScroll(){
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == YourImageList.size()) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
}
};
timer = new Timer(); // creating a new thread
timer .schedule(new TimerTask() { // task to be scheduled
@Override
public void run() {
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.
@Override
public void onDetach() {
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?"