是不是对onActivityCreated片段回调有什么误解?

Is there any misunderstanding about the onActivityCreated fragment callback?

onActivityCreated好像是"This fragment callback is executed just after the activity has been... created... I mean, just after the fragment is correctly attached to the activity. There, you can safely call getActivity, it won't return null, except if the activity is null for some special reason".

的意思

但是,我看到即使在 OnCreate 之后调用了片段回调 onAttach,这意味着该片段已附加到已创建的 activity .

一个片段(以及一个经常被遗忘的片段对话框)的完整工作流程是:onAttach -> onCreate -> onCreateView -> onActivityCreated.因此,在这 4 种方法中的每一种中(也许不是 onAttach 我不知道),activity 通常不为 null 并附加到片段。

所以我的问题是:为什么回调 onActivityCreated 因为 activity 实际上已经创建并附加到片段 3 回调之前???

所以基本上在 onAttach() 中我们得到确认 activity 附加到我的片段,我可以使用 getActivity() 来获取像

这样的资源
getActivity().getResources.getDrawable(R.drawable.abc)

但是假设如果你想获取在 activity 的 xml 中膨胀的视图,比如如果你想访问

getActivity().findViewById(R.id.Myelement)

你可能在这里得到 null,所以 OnActivtyCreated() 确保 activity 的视图被膨胀,你现在可以访问 activity 的视图(Activity 的视图有已创建(在Activity已创建))