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

dav*_*ber 3 android android-fragments android-support-library

我正在使用Fragment带有 Android 支持库 v7 的类。在我ActivityonCreate()方法中,我创建了一堆片段并将它们存储到我的活动的属性中。

this.firstFragment = new FirstFragment();
this.secondFragment = new SecondFragment();
// and so on
Run Code Online (Sandbox Code Playgroud)

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

// Replace the current content of the fragment holder with the selected section fragment.
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, selectedFragment).commit();
Run Code Online (Sandbox Code Playgroud)

这会导致调用onDestroy()已删除的片段。在调用片段后重用片段是否安全onDestroy(),或者我应该在每次向用户显示片段时重新创建片段。

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

Sam*_*awy 5

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

Fragment调用后再次调用,onDestroy会从头开始再次经历生命周期onCreate,所有的variables和本地的object都会重新初始化。

安全吗?是的,它很安全。

您正在更深入地思考如何处理操作系统已经处理的生命周期。Fragment

如果你想防止被Fragment破坏,你可以将其创建为一个static对象。