Removing fragments from FragmentStatePagerAdapter
Your problem is not caused by your use of SparseArray. In fact, you meet a bug of the FragmentStatePagerAdapter. I spent some time reading the source code of FragmentStatePagerAdapter, ViewPager and FragmentManagerImpl and then found the reason why your new fragments have the state of old ones:
The FragmentStatePagerAdapter save the sate of your old fragments when it remove them, and if you add new fragments to you adapter later, the saved state will be passed to your new fragment at the same location.
I googled this problem and find a solution, here is its link: http://speakman.net.nz/blog/2014/02/20/a-bug-in-and-a-fix-for-the-way-fragmentstatepageradapter-handles-fragment-restoration/
The source code can be found here: https://github.com/adamsp/FragmentStatePagerIssueExample/blob/master/app/src/main/java/com/example/fragmentstatepagerissueexample/app/FixedFragmentStatePagerAdapter.java
The key idea of this solution is to rewrite the FragmentStatePagerAdapter and use a String tag to identify each fragment in the adapter. Because each fragment has a different tag, it is easy to identify a new fragment, then don't pass a saved state to a new Fragment.
Finally, say thanks to Adam Speakman who is the author of that solution.
FragmentStatePageAdapter
saves the state of the fragment while destroying it, so that latter when the fragment is recreated the saved state will be applied to it.
The fragment state is stored in a private member variable. Hence we can't extend the current implementation to add the feature of removing the saved state.
I've cloned the current FragmentStatePagerAdapter
implementation and have included the saved state removal functionality. Here is the gist reference.
/**
* Clear the saved state for the given fragment position.
*/
public void removeSavedState(int position) {
if(position < mSavedState.size()) {
mSavedState.set(position, null);
}
}
In your clearProgressUpTo
method, whenever you remove the fragment from sparse array, call this method, which clears off the saved state for that fragment.