Is it safe to reuse Fragment after onDestroy() has been called?
-
23-12-2019 - |
Question
I am using the Fragment
class with the Android support library v7. In my Activity
's onCreate()
method I create a bunch of fragments and store them into properties of my activity.
this.firstFragment = new FirstFragment();
this.secondFragment = new SecondFragment();
// and so on
I use the navigation drawer pattern to switch between the fragments of my app. To change the active fragment I use following code.
// Replace the current content of the fragment holder with the selected section fragment.
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, selectedFragment).commit();
This results in a call to onDestroy()
of the removed fragment. Is it safe to reuse the fragment after it's onDestroy()
has been called, or should I recreate the fragment every time it is shown to the user.
This is a question of time vs. memory consumption, as at least one of the fragments needs some time to get created.
Solution
onDestroy
functionality is to destroy all the used variables and consumed memory. All those will be flagged as a Dummy data to enable the garbage collector
to remove them from the memory whenever it is needed.
Calling the Fragment
again after calling onDestroy
will pass through the lifecycle again from the beginning through onCreate
and all the variables
and local object
will be re-initialized again.
Is it Safe? Yes, it is safe.
You are thinking deeper to handle the lifeCycle of the Fragment
that is already being handled by the OS.
If you want to prevent the Fragment
from being destroyed you can create it as a static
object.
OTHER TIPS
The Fragments developer guide seems to tell no, according to the lifecycle diagram.
If you want to keep your fragment for a later use, i suggest you use FragmentTransaction.detach(Fragment)
or FragmentTransaction.hide(Fragment)
instead of FragmentTransaction.remove(Fragment)
.