Why is onAttach called before onCreate?

前端 未结 4 614
暗喜
暗喜 2020-12-13 05:56

In a Fragment\'s Lifecycle, the onAttach() method is called before the onCreate() method. I can\'t wrap my head around this. Why would you attach a Fragment first?

4条回答
  •  孤街浪徒
    2020-12-13 06:17

    Because onAttach() assigns hosting activity to the Fragment. If it had been called after onCreate() then there would be no context for your fragment (getActivity() would return null) and you would not be able to do anything in onCreate() method without that context anyway.

    Another fitting reason is that Fragment's lifecycle is similar to Activity's lifecycle. In Activity.onAttach() activity gets attached to its parent (a window). Similarly in Fragment.onAttach() fragment gets attached to its parent (an activity), before any other initialization is done.

提交回复
热议问题