why we can call getActivity() in onCreateView which run before onActivityCreated?

梦想的初衷 提交于 2019-12-17 21:03:52

问题


I really get confused with Fragment lifecycle, especially for the time to call getActivity(). Sometimes you cannot get Activity by getActivity(). And it always caused some puzzling bugs.
Thank you for anyone can solve the puzzle.


回答1:


getActivity() can be null while your fragment is in process of preparation and about to be ready.

The fragment life cycle is bound to callback methods. These method will be called somewhere in time while fragment is preparing.

  • Fragment.onActivityCreated(Bundle) is the place when the fragment activity will not be null, i.e. getActivity() will be a valid instance. It happens after onCreateView() though

Your safest bet for activity existence is:

  • Fragment.onViewCreated(View, Bundle)
  • Fragment.onStart()



回答2:


According to the current documentation (Dec 2018), it shows that onAttach() is called right at the beginning before onCreate() and onCreateView(). It should be safe to getActivity() in these methods.


In the Support v4 Fragment documentation for onActivityCreated() it says that this method is:

Called when the fragment's activity has been created and this fragment's view hierarchy instantiated.

The important part here is that the "activity has been created" i.e. Activity.onCreate() has finished executing. Before this point we are still within that method.

This can be confirmed by looking at the FragmentActivity.onCreate() source code you can follow the process of fragments being attached to the activity at the start of the method, then the fragment state being restored etc etc. So the activity should be valid in all those places, but technically it has not finished with the whole create process.



来源:https://stackoverflow.com/questions/31236451/why-we-can-call-getactivity-in-oncreateview-which-run-before-onactivitycreated

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