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

前端 未结 2 798
轮回少年
轮回少年 2020-12-11 14:35

I really get confused with Fragment lifecycle, especially for the time to call getActivity(). Sometimes you cannot get Activity by

相关标签:
2条回答
  • 2020-12-11 15:12

    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.

    0 讨论(0)
  • 2020-12-11 15:28

    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()
    0 讨论(0)
提交回复
热议问题