6

I have got a ViewPager which is populated by a FragmentPagerAdapter. I want to change from the first adapter two another. The problem is that all pages which were loaded before (while having the first adapter) are still the old ones.

I looked at the source code of FragmentPagerAdapter and guess the problem occurs because of the instatiateItem() implementation. Using the tag, which has position and conatiner id in it, the method checks if there is already a Fragment at the position. When there is a Fragment with this tag it is attached. The container id and position do not change when setting a new adapter so it finds the old Fragments.

Do you know a way to remove all old fragments?

Gabriel Ittner
  • 1,162
  • 9
  • 22

1 Answers1

11

I realized that the Fragment tag uses an id, obtained by getItemId() and not the position. To solve my issue I have overwritten getItemId() and use totally different ids in the different FragmentPagerAdapters.

@Override
public long getItemId(int position) {
    return mPagerId*100+position;
}

mPagerId is an unique integer that is assigned in the constructor. If you have more than 100 pages you should replace 100 with 1000.

Gabriel Ittner
  • 1,162
  • 9
  • 22
  • @AntonM. It works very well on HTC legend with android 2.2, Thanks gabriel – Ali Jul 11 '13 at 10:29
  • 1
    Unfortunately this solution will cause a memory leak since all the previous page fragments will stay in memory inside the fragment manager - you can easily check that by using getFragmentSupportManager().getFragments(). Generating new ids will just force the PagerAdapter to create new pages without removing the ones with the old ids... – Nati Dykstein Sep 04 '15 at 14:04