Android Fragment onCreateView 与 onActivityCreated

发布于 2024-12-14 07:06:29 字数 247 浏览 5 评论 0原文

我知道片段的视图层次结构必须在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

短暂陪伴 2024-12-21 07:06:29

如果您的视图是静态的,则无需将任何代码移至 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.

以酷 2024-12-21 07:06:29

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 use onViewCreated() 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文