I have implemented the FragmentPagerAdapter
and and using a List
to hold all fragments for my ViewPager
to display. On
Taking "the best of both worlds" (I mean the answers by @Tericky Shih and @mikepenz) we have it short and simple:
public class MyPagerAdapter extends FragmentPagerAdapter {
public ArrayList fragments = new ArrayList();
...
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
if (position >= getCount()) fm.beginTransaction().remove((Fragment) object).commit();
}
@Override
public int getItemPosition(Object object) {
if (fragments.contains(object)) return fragments.indexOf(object);
else return POSITION_NONE;
}
}
The main difference is that if some fragment is not changed you don't have to destroy its view and don't have to return POSITION_NONE
for it. At the same time, I've encountered a situation when ViewPager was holding a reference to an item which was already destroyed, therefore the check if (fragments.contains(object))
helps to determine if that item is not needed anymore.