3

Is it OK to keep an instance of every fragment that is created for a FragmentPagerAdapter inside the FragmentPagerAdapter?

Something like this:

@Override
    public Object instantiateItem(ViewGroup container, int position)
        switch(position){
        case 0:
            fragment0 = super.instantiateItem(container, position);
            return fragment0;
        case 1:
            fragment1 = super.instantiateItem(container, position);
            return fragment1;
        default:
            return super.instantiateItem(container, position);
        }
    }

Will I run into memory issues?

The idea is to do something like MyFragmentPagerAdapter.fragment0 in order to get a reference to the fragment.

Mayur Birari
  • 5,837
  • 8
  • 34
  • 61
Héctor Júdez Sapena
  • 5,329
  • 3
  • 23
  • 31

1 Answers1

8

The problem with that approach is that the FragmentManager may create new instances of a fragment even if you maintain a reference. In that situation, several instances of the same fragment would be in memory (leak) and the reference you maintain targets an instance that might not even be displayed. So in other words it is not safe.

What is safe however is to maintain a reference of your activity in your fragments.

In your fragment you override

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    home = (YourFragmentActivity) activity;
}

public void onCreate(Bundle savedInstanceState) {
            home.setThisFragTag(getTag());
    }

In your FragmentActivity

public void ThisFragTag(String tag) {
    this.fragTag = tag;
}

Now in your activity you can get a hold to the fragment instance currently displayed with

(YourFragmentClass) getSupportFragmentManager().findFragmentByTag(fragTag);

You can repeat this operation for several fragments

znat
  • 13,144
  • 17
  • 71
  • 106
  • Actually, I think with my approach I always keep a reference to the actual instance of the fragment that is being managed by the fragmentManager. However I prefer your suggestion. Thanks! – Héctor Júdez Sapena Dec 03 '12 at 17:51