0

I have a ViewPager and ViewPagerAdapter as defined below:

private static class ViewPagerAdapter extends FragmentPagerAdapter {
        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public Fragment getItem(int position) {

            return fragments.get(position);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
}

Within my activity I am populating fragments array which is my list of Fragments which I can view by scrolling horizontally:

// populate fragments
fragments.add(....);
pager_adapter = new ViewPagerAdapter(getSupportFragmentManager());
view_pager.setAdapter(pager_adapter);

All this works fine. But, now I have a situation where in at run time I have to add one more fragment to this list and then refresh the view so that the new fragments becomes visible too upon scrolling. For this I added the following code inside my activity:

public static void addPageAndRefresh(Page page) {
    fragments.add(PinFragment.newInstance(fragments.size(), true, page, book, false, false, null));
    pager_adapter.notifyDataSetChanged();
}

After this, I do get a new fragment, but it is not the one which I added, its a copy of the last fragment in the last before calling notifyDataSetChanged().

Is this the correct way of doing this? It looks like although the fragments array is updated properly, but the view is not picking up the updated array. But, if it isn't then I shouldn't be seeing the new fragment after scrolling.

pankaj
  • 1,316
  • 3
  • 16
  • 27

1 Answers1

0

I tried similar requirement as yours with a FragmentStatePagerAdapter which worked fine. May be you would want to try it.

To add the new fragment:

SIZE = SIZE +1;
adapter.instantiateItem(viewPager, SIZE-1);
adapter.notifyDataSetChanged();

In getItem(), for the "position" create and return the new fragment (I used a switch statement here)

Update the getCount() method to return the new SIZE.

Let me know if you would like me to share the code.

hrushi
  • 294
  • 1
  • 10
  • Yeah, I found a similar solution here in this post - http://stackoverflow.com/questions/10849552/update-viewpager-dynamically?rq=1 and tried FragmentStatePagerAdapter. Things are working fine. Thanks ! – pankaj May 19 '16 at 03:20