片段中onCreate()、onCreateView()和onActivityCreated()的区别和使用 [英] Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments
问题描述
onCreate()
、onCreateView()
和 onActivityCreated()
在片段中的区别是什么,它们各自的用途是什么为了?
What are the differences between onCreate()
, onCreateView()
, and onActivityCreated()
in fragments and what would they each be used for?
推荐答案
更新:
onActivityCreated()
已从 API 级别 28 中弃用.
onActivityCreated()
is deprecated from API Level 28.
onCreate():
Fragment
中的 onCreate()
方法在 Activity
的 onAttachFragment() 之后被调用code> 但在
Fragment
的 onCreateView()
之前.
在此方法中,您可以分配变量、获取 Intent
附加项,以及任何其他不涉及视图层次结构的内容(即非图形初始化).这是因为这个方法可以在Activity
的onCreate()
没有完成的时候被调用,所以尝试访问这里的View层级可能会导致崩溃.
The onCreate()
method in a Fragment
is called after the Activity
's onAttachFragment()
but before that Fragment
's onCreateView()
.
In this method, you can assign variables, get Intent
extras, and anything else that doesn't involve the View hierarchy (i.e. non-graphical initialisations). This is because this method can be called when the Activity
's onCreate()
is not finished, and so trying to access the View hierarchy here may result in a crash.
onCreateView():
onCreate()
被调用后(在Fragment
中),Fragment
的onCreateView()
被调用.您可以分配View
变量并进行任何图形初始化.你应该从这个方法返回一个 View
,这是主 UI 视图,但是如果你的 Fragment
不使用任何布局或图形,你可以返回 null
(如果您不覆盖,则默认发生).
After the onCreate()
is called (in the Fragment
), the Fragment
's onCreateView()
is called. You can assign your View
variables and do any graphical initialisations. You are expected to return a View
from this method, and this is the main UI view, but if your Fragment
does not use any layouts or graphics, you can return null
(happens by default if you don't override).
onActivityCreated():
顾名思义,这是在Activity
的onCreate()
完成后调用.它在 onCreateView()
之后调用,主要用于最终的初始化(例如,修改 UI 元素).这是从 API 级别 28弃用.
As the name states, this is called after the Activity
's onCreate()
has completed. It is called after onCreateView()
, and is mainly used for final initialisations (for example, modifying UI elements). This is deprecated from API level 28.
总结...
...它们都在 Fragment
中被调用,但在不同的时间被调用.onCreate()
首先被调用,用于进行任何非图形初始化.接下来,您可以分配和声明您想要在 onCreateView()
中使用的任何 View
变量.之后,使用 onActivityCreated()
来做任何你想在一切都完成后做的最终初始化.
To sum up...
... they are all called in the Fragment
but are called at different times.
The onCreate()
is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View
variables you want to use in onCreateView()
. Afterwards, use onActivityCreated()
to do any final initialisations you want to do once everything has completed.
如果您想查看官方 Android 文档,可以在这里找到:
If you want to view the official Android documentation, it can be found here:
Stack Overflow 上还有一些稍微不同但不太成熟的问题/答案:
这篇关于片段中onCreate()、onCreateView()和onActivityCreated()的区别和使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!