1

I have a ViewPager with 10+ views. I wish to change the order of the pages occasionally i.e.

Page 1 | Page 2 | page 3

to

Page 3 | Page 1 | Page 2

For the tabs I am using ViewPagerIndicator, I am able to update the order of these by changing the order of my adapter and calling:

mViewPagerIndicator.notifyDataSetChanged();

However, what I cannot update is the content of the ViewPager, for example if I update the ViewPager adapter (to the new order I wish the pages to be in) and call:

mViewPager.getAdapter().notifyDataSetChanged()

This has no effect. The tab indicator bar is updated fine but the content of the page still shows the old order.

Is there a way to change the order of pages in a ViewPager adapter and get the ViewPager to reload all it's views?


My ViewPager adapter extends FragmentStatePagerAdapter and my overridden methods are as follows:

@Override
public Fragment getItem(int position) {
    return MyCustomFragment.newInstance();
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    //super.destroyItem(container, position, object);  // Commented out to ensure views are not destroyed
}

Thanks

Mylo
  • 87
  • 4
  • 13

2 Answers2

1

It's tricky to do with FragmentStatePagerAdapter because you'll have to implement the logic yourself, but it's a lot easier with FragmentPagerAdapter which already provides the functionality for this purpose.

Calling .notifyDataSetChanged() invokes the getItemPosition(Object object)-method of your adapter. This is where you should provide ViewPager with the information of where to put the Fragment passed in the parameter object, by returning the page-number you want the Fragment to be positioned on.

For an example on how to do this, check out my answer here.

Community
  • 1
  • 1
Reinier
  • 3,836
  • 1
  • 27
  • 28
0

If performance isn't super important, it's really easy to force the FragmentStatePagerAdapter or FragmentPagerAdapter to redraw (invalidate) all of its views/fragments: just override getItemPosition and call notifyDataSetChanged() as you normally would.

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE; //In source code, POSITION_NONE = -2 FYI
}

For more info, check out my post: How to use orderByKey() in descending order instead of ascending #Askfirebase

tmthydvnprt
  • 10,398
  • 8
  • 52
  • 72
SUPERCILEX
  • 3,929
  • 4
  • 32
  • 61