内部保持FragmentPagerAdapter片段的实例 [英] keep instances of fragments inside FragmentPagerAdapter

查看:138
本文介绍了内部保持FragmentPagerAdapter片段的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否正常,保持了 FragmentPagerAdapter FragmentPagerAdapter ?<创建的每个片段的一个实例/ P>

事情是这样的:

  @覆盖
    公共对象instantiateItem(ViewGroup中的容器,INT位置)
        开关(位置){
        情况下0:
            fragment0 = super.instantiateItem(集装箱,位置);
            返回fragment0;
        情况1:
            片段1 = super.instantiateItem(集装箱,位置);
            返回片段1;
        默认:
            返回super.instantiateItem(集装箱,位置);
        }
    }
 

我会遇到内存问题?

我们的想法是做类似 MyFragmentPagerAdapter.fragment0 为了得到一个参考片段。

解决方案

与该方法的问题是, FragmentManager 可能会创建一个片段,即使你保持新实例参考。在这种情况下,同一片段的几个实例是在存储器(泄漏)和参考你保持目标可能甚至不被显示的实例。因此,换句话说,它是不是安全的。

然而什么是安全是维护你的活动的参考您的片段。

在你的片段重写

  @覆盖
公共无效onAttach(活动活动){
    super.onAttach(活动);
    家庭=(YourFragmentActivity)的活动;
}

公共无效的onCreate(包savedInstanceState){
            home.setThisFragTag(getTag());
    }
 

在你FragmentActivity

 公共无效ThisFragTag(字符串标签){
    this.fragTag =标签;
}
 

现在在你的活动,你可以得到一个抱到目前与

显示片段实例

 (YourFragmentClass)getSupportFragmentManager()findFragmentByTag(fragTag)。
 

您可以重复此操作几个片段

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.

解决方案

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

这篇关于内部保持FragmentPagerAdapter片段的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆