为什么OnCreate更喜欢执行所有主要的应用程序任务?

发布于 2025-01-21 05:00:50 字数 245 浏览 3 评论 0原文

为什么onCreate()更喜欢执行所有主要应用程序任务?为什么不onResume()onstart()?为什么只有ongreate()?我尝试执行主要任务,例如binding findViewById()将文本设置为文本视图等等。他们都可以正常工作。何时我们总是更喜欢在increate()中执行该任务?

Why Is onCreate() Preferred To Do All The Main App Tasks? Why not onResume() or onStart()? Why only onCreate()? I tried to do the main tasks like binding findViewById() setting text to text views and a lot more. They all work fine. When why do we always are preferred to do that task in onCreate()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

喜爱皱眉﹌ 2025-01-28 05:00:50

OnCreate是您活动中的第一个入口点,因此从逻辑上讲,在此处尽可能多地进行初始化是有意义的。通常情况下,在某些情况下,需要更高的优先级配置事物 - 崩溃报告服务,依赖注入等。

根据

受保护的void ongreate(捆绑savedinstancestate)

活动开始时调用。 这是大多数初始化应该进行的:调用SetContentView(INT)以使用FindViewById(INT)来夸大活动的UI,以编程与UI ...

中的小部件进行编程交互。

因此,我认为这是公平的假设大多数初始化将在OnCreate内部完成,这通常意味着,如果您将其放入可以反复执行的生命周期方法中,则可以将其视为冗余,因为您将分配分配该方法反复对变量的值相同,除非您实际上想做的。

但是,懒惰的初始化也是要牢记的概念,能够初始化ongreate内部的某些东西并不总是意味着您应该应该延迟初始化,直到您实际需要实例为止。

关于

我尝试执行主要任务,例如将文本设置为文本视图等等,等等。他们都可以正常工作。

他们肯定会使用,FindViewById可以始终使用,并且不仅限于在OnCreate内部,实际上,FindViewById的结果甚至不必分配给变量才能使您能够使用它

OnCreate serves as the first entry point into your activity, so logically it makes sense to do as much of the initialization here as possible. Often times there are cases when things need to get configured with higher priority - crash reporting services, dependency injection etc. where this would get escalated to a custom application class.

according to the docs

protected void onCreate (Bundle savedInstanceState)

Called when the activity is starting. This is where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById(int) to programmatically interact with widgets in the UI...

so, I suppose it is fair to say that most initialization will get done inside of onCreate, which usually means that if you were to place this into a lifecycle method which could get executed repeatedly, that could be considered redundant as you'd be assigning the same values to variables repeatedly, unless that's something you actually want to do.

However, lazy initialization is also a concept to keep in mind, being able to initialize something inside of onCreate doesn't always mean that you should, it is often times better to delay initialization until you actually need the instance.

regarding

I tried to do the main tasks like binding findViewById() setting text to text views and a lot more. They all work fine.

they definitely would, findViewById can always be used and isn't limited to being inside of onCreate, in fact the result of findViewById doesn't even have to be assigned to a variable for you to be able to use it

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