Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewPager switch FragmentPagerAdapter

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?

like image 846
Gabriel Ittner Avatar asked Jul 26 '12 14:07

Gabriel Ittner


1 Answers

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.

like image 122
Gabriel Ittner Avatar answered Nov 15 '22 04:11

Gabriel Ittner