keep instances of fragments inside FragmentPagerAdapter

谁说胖子不能爱 提交于 2019-12-01 09:13:01

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

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