Fragment onStop() versus onDetach(), onDestroy() or onDestroyView() of the same?

你。 提交于 2019-12-08 09:16:22

问题


This is the question worth to be asked on the behalf of the new developers in Android.

Idea is to provide a deep understanding to why the framework is written as such. Also, developers face dangling pointers, illegal states and such run-time crashes, and they do not have a clue that why it is happening.

Programmers now a days heavily use call back and factory patterns. Use of delegate class objects reduce the need for Singleton classes, and the need of multiple inheritance in languages like C, C++.

Developers thrill when they come to understand Handler based message passing between components.

Which one of these methods is more reliable to know that the context of the Fragment, should no longer be used by its components, or outside from the Activity that is parenting it:

  1. onStop()
  2. onDetach()
  3. onDestroyView()
  4. onDestroy()

Best Regards.


回答1:


Kindly go through this link to understand the lifecycle of Fragments

It says that while your current fragment (you can track using getter and setter in Application extended class) is in dying phase, getView(), and getActivity() will return null. So you should not be using these methods and be cautious of the concerned life cycle callbacks (again can be tracked using boolean getters and setters in the abstract BaseFragment/BaseActivity sub-classes of the regular concrete Fragments and Activity classes).

source




回答2:


I am tracking all of these methods, to stop using getView() of fragment. I logically feel onDestroy(), is the most suitable method for this purpose.

I am using the trackers in the same way in this answer: https://stackoverflow.com/a/52017405/787399

This inheritance strategy greatly helps and improves the meaning of the Activity and Fragments life-cycles. I fact it is so power full that you can have those features that are not implicitly provided: Like you can handle system back press (managed in the BaseActivity in onBackPressed() method) whenever back is pressed on the Fragment, and you can block the back pressed event call, till some condition is met, or place an OK_Cancel confirmation alert, that whether you want to really exit the current fragment.

Happy coding :-)



来源:https://stackoverflow.com/questions/52017291/fragment-onstop-versus-ondetach-ondestroy-or-ondestroyview-of-the-same

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