Somebody told me the following, but I am a bit perplexed.
Please, would you be able to confirm or dispute it?
(the Fragment is
I don't think there is a direct official answer, but the answer is in the documentation and it can be easily proven. If you check fragment lifecycle and description of onDestroyView method, it says:
onDestroyView
is called the layout is detached and next time fragment attaches the view is recreated.onCreateView
is called in this case. That basically means if you keep any view references in the fragment instance while the fragment is in back stack, you are preventing these views from being garbage collected.
If you are still not convinced, you can take a look at the source code of AOSP. For example ListFragment and PreferenceFragment both set all views references to null in onDestroyView()
.
In addition it's pretty easy to prove there is a memory leak. Just create a fragment with an image view, which displays a full-size image. Keep a reference in your fragment and navigate to another fragment with a fragment transaction. Then tap force garbage collection
button and create a heap dump with the memory profiler tool and you'll see your fragment is actually holding image view and the image itself, preventing them from being collected. If you repeat the same steps, but setting the reference to null in onDestroyView()
, you'll see your fragment's retained size is much smaller and no ImageView
instance is present in the heap anymore.