Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reusing fragments in a fragmentpageradapter

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));     } } 
like image 984
jwanga Avatar asked Aug 07 '11 21:08

jwanga


People also ask

Is it possible to reuse a fragment in multiple screens?

Yes you can, but you have to add more logic to your fragments and add some interfaces for each activity.

How to reuse same Fragment for viewpager in android?

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.


2 Answers

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.

like image 148
Geoff Avatar answered Oct 16 '22 13:10

Geoff


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

like image 39
petrnohejl Avatar answered Oct 16 '22 13:10

petrnohejl