keep instances of fragments inside FragmentPagerAdapter

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.

Upvotes: 3

Views: 2988

Answers (1)

znat
znat

Reputation: 13474

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

Upvotes: 8

Related Questions