Android Fragment onCreateView 与 onActivityCreated
我知道片段的视图层次结构必须在 onCreateView 中扩充,但是 onCreateView 中还可以包含哪些其他功能,而不是应该等待 onActivityCreated?我当前的实现对所有内容都使用单独的活动,典型的活动在其 onCreate 方法中完成大部分工作,包括膨胀视图、设置内容视图、使用数据初始化各种小部件、设置侦听器等。
所以这可能是全部转移到 onCreateView 中,还是应该将某些函数放入 onActivityCreated 方法中?
I know that a fragment's view hierarchy has to be inflated in onCreateView, but what other functionality can be in onCreateView vs. what should wait for onActivityCreated? My current implementation uses separate activities for everything, and a typical activity does most of its work in its onCreate method, including inflating the view, setting the content view, initializing the various widgets with data, setting up listeners, etc.
So can this probably all be moved into onCreateView, or should some functions be put into an onActivityCreated method instead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的视图是静态的,则无需将任何代码移至 onActivityCreated 方法。但是,例如,当您从适配器填充一些列表时,您应该在 onActivityCreated 方法中执行此操作,并在 setRetainInstance 执行此操作时恢复视图状态。
此外,访问父 Activity 的视图层次结构必须在 onActivityCreated 中完成,而不是更早。
If your view is static, then moving any code to the onActivityCreated method is not necessary. But when you - for instance, fill some lists from the adapter, then you should do it in the onActivityCreated method as well as restoring the view state when setRetainInstance used to do so.
Also accessing the view hierarchy of the parent activity must be done in the onActivityCreated, not sooner.
onActivityCreated()
已在片段中弃用1.3.0-alpha02,建议使用onViewCreated()
代替。这里已经创建了视图,您可以设置侦听器、从 ViewModel 观察 LiveData、初始化 recyclerView 等。为了更好地理解,您可以查看我的博客文章,其中我描述了 Android Fragment 生命周期 在 137 秒内。
onActivityCreated()
is deprecated in fragment 1.3.0-alpha02 and there is a recommendation to useonViewCreated()
instead. View is already created here and you can set listeners, observe LiveData from ViewModel, initialize recyclerView, etc.For a better understanding, you can take a look at my blog post, where I describe the Android Fragment lifecycle in 137 seconds.