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

前端 未结 2 797
轮回少年
轮回少年 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: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()

提交回复
热议问题