Activity's onDestroy / Fragment's onDestroyView set Null practices

泪湿孤枕 提交于 2019-11-28 03:49:46

So the reason it's different between Fragments and Activities is because their lifecycles are different. When an Activity is destroyed, it's going away for good. However, Fragments may create and destroy their views multiple times before they're actually destroyed. For clarification, in an Activity:

onDestroy()
onCreate()

will never happen in sequence for the same Activity instance. For a Fragment, the following is perfectly valid:

onCreate()
onCreateView()
onDestroyView()
onCreateView()
onDestroyView()
onDestroy()

One case where you can see this is when a Fragment goes into the back stack. Its view will be destroyed (as it is no longer visible) but the instance will remain around to be easily resumed when the user presses back to return to it (at which point onCreateView() will again be called).

After onDestroyView(), you can (and likely should) release all of your View references to allow them to be garbage collected. In many cases, it's not necessary, as if it's just happening during a configuration change, onDestroy() will immediately follow and the whole instance will be garbage collected.

Essentially, I would say it is good practice to release any and all view references in onDestroyView(), and could save quite a bit of memory if your app has a large backstack.

No need to set null if that does not influence on logic of the app. E.g. if (mList == null) ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!