I know this post is few months old but i am a beginner at building android applications & I am facing the same problem.
I would try the following approach even if it absolutely does not seem to be optimal....
- Build an array into your adapter class which will contain all of your fragments.
- Populate this array with the fragments you want to display. The trick will be to add the first fragment at the end of the list & remove it after the
ViewPager
has done its changes.
- Override the following methods
getItem(int position)
and getCount()
with your array : return yourFragmentArray.get(position);
& return yourFragmentArray.size();
- The idea is to populate the
ViewPager
with the same fragments over & over again (+ new ones if needed) and delete the one you used to populate the VP so you never go back.
- So if i take your code i would do something like this :
private int size = yourFragmentArray.size();
public void setupAutoPager(final int size) {
final Handler handler = new Handler();
currentPage = promotionViewPager.getCurrentItem();
final Runnable update = new Runnable() {
public void run() {
if (currentPage == size - 1) {
// Add the fragment to your fragmentArray
// Only the rank 0 needs to be taking care, works like in queue
yourFragmentArray.add(yourFragmentArray.get(0));
// Notify the changes made
yourAdapter.notifyDataSetChanged();
// Set the next item
promotionViewPager.setCurrentItem(currentPage + 1);
yourFragmentArray.remove(0);
// Update the size
size += 1;
}
else {
promotionViewPager.setCurrentItem(currentPage + 1);
}
}
};
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(update);
}
}, 500, 2500);
}
The logic is somewhere here for me, again it's probably not the best way to do it but i can't see another for now.
Good luck ! I will update this post as soon as i can test it myself.
UPDATE :
A much better way to do it is to add in this method :
- Save into a specific variable
firstMaxSize
the size of the ViewPager before the method is called.
Use a counter (if it's the first time you loop through the adapter fragments, we won't remove them), but if(counter != 0)
we will loop through the yourFragmentArray()
and remove from 0 to firstMaxSize
.
Call yourAdapter.notifyDataSetChanged()
Then add all over again the new fragments. If the problem of an existing fragment is already added happens, create a new fragment based on the content of this one.
Call again yourAdapter.notifyDataSetChanged()
It is indeed very heavy & i am pretty sure another easiest way exists but have not found it yet.