keep instances of fragments inside FragmentPagerAdapter

我只是一个虾纸丫 提交于 2019-12-01 05:46:01

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/13685099/keep-instances-of-fragments-inside-fragmentpageradapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!