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

后端 未结 3 1870
耶瑟儿~
耶瑟儿~ 2020-12-07 16:38

I am reading ListFragment source code and I see this implementation:

ListAdapter mAdapter;
ListView mList;
View mEmptyView;
TextView mStanda         


        
相关标签:
3条回答
  • 2020-12-07 17:25

    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.

    0 讨论(0)
  • 2020-12-07 17:31

    Since API 19 there is no need to unregister your listeners in onDestroy() and onDestoryView(), the pending click events automatically canceled in onStop().

    And there is no need to set your views to null. Use the ViewBinding from Jetpack.

    So, in the majority of cases, you don't need to implement onDestroyView() in the fragment. For more info, take a look at the blog post about Android Fragment Lifecycle. It'll take you only 137 seconds.

    0 讨论(0)
  • 2020-12-07 17:32

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

    0 讨论(0)
提交回复
热议问题