I have a viewpager that pages through fragments. My FragmentPagerAdapter subclass creates a new fragment in the getItem method which seems wasteful. Is there a FragmentPagerAdapter equivalent to the convertView in the listAdapter that will enable me to reuse fragments that have already been created? My code is below.
public class ProfilePagerAdapter extends FragmentPagerAdapter { ArrayList<Profile> mProfiles = new ArrayList<Profile>(); public ProfilePagerAdapter(FragmentManager fm) { super(fm); } /** * Adding a new profile object created a new page in the pager this adapter is set to. * @param profile */ public void addProfile(Profile profile){ mProfiles.add(profile); } @Override public int getCount() { return mProfiles.size(); } @Override public Fragment getItem(int position) { return new ProfileFragment(mProfiles.get(position)); } }
Yes you can, but you have to add more logic to your fragments and add some interfaces for each activity.
You need a pool to manage the fragment instances. This will create, retain, and destroy (when necessary) the fragment instances. Whenever ViewPagerAdapter. getItem() is called, get a fragment instance from the pool and return it.
The FragmentPagerAdapter already caches the Fragments for you. Each fragment is assigned a tag, and then the FragmentPagerAdapter tries to call findFragmentByTag. It only calls getItem if the result from findFragmentByTag is null. So you shouldn't have to cache the fragments yourself.
Appendix for Geoff's post:
You can get reference to your Fragment in FragmentPagerAdapter using findFragmentByTag(). The name of the tag is generated this way:
private static String makeFragmentName(int viewId, int index) { return "android:switcher:" + viewId + ":" + index; } where viewId is id of ViewPager
Look at this link: http://code.google.com/p/openintents/source/browse/trunk/compatibility/AndroidSupportV2/src/android/support/v2/app/FragmentPagerAdapter.java#104
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With