I currently have a basic ViewPager
that utilizes a FragmentStatePagerAdapter
to initialize fragments.
This ViewPager
starts at the end and scrolls backwards (i.e. scrolls to the left).
As the user nears the start of the ViewPager
's list, I want there to be more items added to the start of the adapter's list programmatically, essentially creating an infinitely scrollable ViewPager
(going left) without disrupting the user's experience (i.e. not reloading their current fragment as the ViewPager has fragments added on to it). However, I am unable to accomplish this.
Currently, I am detecting when my adapter's getItem()
function passes a position of 0, populating the start of the list the adapter uses with more items, and then calling notifyDataSetChanged()
. However, what happens is that the fragments at position 1 (which triggers the getItem()
call as soon as it comes into focus) and 0 remain at the start of the ViewPager
and the new fragments are loaded all out of order.
Here is my FragmentStatePagerAdapter
:
class WeekyMoodFragmentAdapter extends FragmentStatePagerAdapter {
private final int NUM_WEEKS_TO_INITIALIZE = 4;
private final List<Long> timestampList = new ArrayList<>();
private final ViewPager mViewPager;
WeekyMoodFragmentAdapter(FragmentManager fragmentManager, ViewPager viewPager) {
super(fragmentManager);
mViewPager = viewPager;
initializeTimestampList();
}
private void initializeTimestampList() {
DateTime mondayOfThisWeek = new DateTime(System.currentTimeMillis());
while (mondayOfThisWeek.getDayOfWeek() != DateTimeConstants.MONDAY) {
mondayOfThisWeek = new DateTime(mondayOfThisWeek.getMillis()
- TimeUnit.HOURS.toMillis(DateTimeConstants.HOURS_PER_DAY));
}
long weekStartMS = mondayOfThisWeek.withTimeAtStartOfDay().getMillis()
- TimeUnit.DAYS.toMillis(DateTimeConstants.DAYS_PER_WEEK * NUM_WEEKS_TO_INITIALIZE);
addTimestampsToList(weekStartMS);
}
private void addTimestampsToList(long weekStartMS) {
for (int i = 0; i < NUM_WEEKS_TO_INITIALIZE; ++i) {
weekStartMS += TimeUnit.DAYS.toMillis(DateTimeConstants.DAYS_PER_WEEK);
timestampList.add(i, weekStartMS);
}
notifyDataSetChanged();
}
@Override
public Fragment getItem(int position) {
Fragment fragment = WeeklyMoodFragment.newInstance(timestampList.get(position));
if (position == 0) {
addTimestampsToList(timestampList.get(position)
- TimeUnit.DAYS.toMillis
(DateTimeConstants.DAYS_PER_WEEK * (NUM_WEEKS_TO_INITIALIZE+1)));
}
return fragment;
}
@Override
public int getCount() {
return timestampList.size();
}
}
And how I initialize my ViewPager
:
ViewPager moodViewPager = (ViewPager) view.findViewById(R.id.weeklyMoodViewPager);
moodViewPager.setAdapter(new WeekyMoodFragmentAdapter(getChildFragmentManager());
moodViewPager.setCurrentItem(moodViewPager.getAdapter().getCount());