Why is onAttach called before onCreate?

前端 未结 4 603
暗喜
暗喜 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:22

    Two Points from Android developer Site hints at why onAttach() is called before onCreate() in case of Fragment Life cycle.

    1. A fragment must always be embedded in an activity. Now this means for Fragment to EXIST, there has to be a "living" Activity.
      Also, When you add a fragment as a part of your activity layout, it lives in a ViewGroup inside the activity's view hierarchy.

    So Fragment must FIRST "attach" itself to activity to defines its own view layout

    1. onCreateis Called to do initial creation of a fragment.

    It is obvious that you will create something only when its pre-condition of creation is in place (and the pre-condition is A fragment must always be embedded in an activity, and it must be attached to its Activity)

提交回复
热议问题