Last active
January 11, 2024 16:42
-
-
Save nesquena/c715c9b22fb873b1d259 to your computer and use it in GitHub Desktop.
Android SmartFragmentStatePagerAdapter that intelligently caches the Fragments in the ViewPager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Extension of FragmentStatePagerAdapter which intelligently caches | |
all active fragments and manages the fragment lifecycles. | |
Usage involves extending from SmartFragmentStatePagerAdapter as you would any other PagerAdapter. | |
*/ | |
public abstract class SmartFragmentStatePagerAdapter extends FragmentStatePagerAdapter { | |
// Sparse array to keep track of registered fragments in memory | |
private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>(); | |
public SmartFragmentStatePagerAdapter(FragmentManager fragmentManager) { | |
super(fragmentManager); | |
} | |
// Register the fragment when the item is instantiated | |
@Override | |
public Object instantiateItem(ViewGroup container, int position) { | |
Fragment fragment = (Fragment) super.instantiateItem(container, position); | |
registeredFragments.put(position, fragment); | |
return fragment; | |
} | |
// Unregister when the item is inactive | |
@Override | |
public void destroyItem(ViewGroup container, int position, Object object) { | |
registeredFragments.remove(position); | |
super.destroyItem(container, position, object); | |
} | |
// Returns the fragment for the position (if instantiated) | |
public Fragment getRegisteredFragment(int position) { | |
return registeredFragments.get(position); | |
} | |
} |
I'm getting FragmentStatePagerAdapter cannot be applied to (android.app.FragmentManager)
on the line:
public SmartFragmentStatePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
Do you know what might be causing this?
EDIT:
I had to change:
import android.app.Fragment;
import android.app.FragmentManager;
to:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
I'm still having trouble getting this to work after rotation. Is there an example project?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@nesquena
Above code works great, just checked. One small correction to the above code, a type cast is required for the return statement -
To simplify the class, I think we can have only one method instead of two doing the same work of getting the Registered Fragment -
Wish I had this code earlier. I came across such a situation, and did not know what to do. Spent a lot of time, and finally made a hack from reading the internal code of
FragmentStatePagerAdapter
. Below is what I came up with, but your solution is very simple.