在调用onDestroy()之后重用Fragment是否安全?

时间:2014-02-27 15:01:33

标签: android android-fragments android-support-library

我正在使用Android支持库v7的Fragment类。在我的Activity的{​​{1}}方法中,我创建了一堆片段并将它们存储到我的活动属性中。

onCreate()

我使用导航抽屉图案在我的应用程序的片段之间切换。要更改活动片段,请使用以下代码。

this.firstFragment = new FirstFragment();
this.secondFragment = new SecondFragment();
// and so on

这会导致调用已删除片段的// Replace the current content of the fragment holder with the selected section fragment. FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.container, selectedFragment).commit(); 。在调用onDestroy()之后重用片段是否安全,或者每次向用户显示片段时都应该重新创建片段。

这是时间与内存消耗的问题,因为至少有一个片段需要一些时间来创建。

2 个答案:

答案 0 :(得分:3)

onDestroy功能是销毁所有使用的变量和消耗的内存。所有这些都将被标记为虚拟数据,以使garbage collector能够在需要时将其从内存中删除。

致电Fragment后再次致电onDestroy将从头开始再次通过生命周期onCreate,所有variables和本地object将会再次重新初始化。

安全吗?是的,这是安全的。

您正在考虑更深入地处理已由操作系统处理的Fragment lifeCycle

如果要阻止Fragment被销毁,可以将其创建为static对象。

答案 1 :(得分:1)

根据生命周期图,Fragments developer guide似乎没有说明。

如果您希望将片段保留供以后使用,建议您使用FragmentTransaction.detach(Fragment)FragmentTransaction.hide(Fragment)代替FragmentTransaction.remove(Fragment)

相关问题