Somebody told me the following, but I am a bit perplexed.
Please, would you be able to confirm or dispute it?
(the Fragment is
Disclaimer:
I will post another answer because I think I couldn't extract the exact use case from the question in the first read. I am waiting for the approval of the edit request I made to this question to know I understood the question properly. I am keeping this answer because I believe there are some useful tips and links that might help someone. On the other hand, in certain cases my answer is right.
Keeping a reference to a View in a Fragment causes memory leaks?
ABSOLUTELY NOT since the field is declared private
, no object from outside of the Fragment
i.e. Activity
can access a hard reference of it from the Fragment
object. Therefore, it will not prevent the Fragment
object from being garbage collected.
You might ask, will it cause memory leak when I use this reference in an async callback?
My answer would be, yes it will cause memory leak for keeping reference inside the async callback but not due to keeping its reference in the
Fragment
. However, this memory leak will also happen even if you don't store theView
reference in theFragment
.
In general, to avoid memory leak, you should watch out the following simple patterns,
This official video, DO NOT LEAK VIEWS (Android Performance Patterns Season 3 ep6) will help you understand it better.