简体   繁体   English

Android活动和片段生命周期-我需要在代码中使用所有方法吗?

[英]Android activity and fragment life cycle - do I need to use all methods in my code?

Android activity and fragment lifecycles have many stages (onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy(), etc). Android活动和片段生命周期有很多阶段(onCreate(),onStart(),onResume(),onPause(),onStop(),onDestroy()等)。 I have been coding in Android Studio for a few months now and there're many times where I haven't used all of lifecycle methods. 我已经在Android Studio中编码了几个月了,很多时候我没有使用所有生命周期方法。

My question is that do you need to use all of the lifecycle methods of a fragment or an activity to write a good code? 我的问题是,您是否需要使用片段或活动的所有生命周期方法来编写良好的代码? Will it cause crashes otherwise? 否则会导致崩溃吗?

Nope. 不。 You can override those methods to add more functionality to your app but those methods already have their own function and will run whether you override it or not. 您可以覆盖这些方法以向应用程序添加更多功能,但是这些方法已经具有自己的功能,并且无论是否覆盖它都将运行。

You could read more on the Android Activity Life Cycle: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle 您可以阅读有关Android活动生命周期的更多信息: http : //developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

You could see this post as well: Android activity life cycle - what are all these methods for? 您也可以看到这篇文章: Android活动生命周期-所有这些方法都有哪些用途?

No, You dont need to write all the lifecycle. 不,您不需要编写所有生命周期。 But you should have the idea of what lifecycle is going on and what will be the behaviour of Android app. 但是您应该对生命周期正在进行以及Android应用程序的行为有一个想法。 Like why you have to attach activity context to fragment context in onAttach() life cycle method. 就像为什么必须在onAttach()生命周期方法中将活动上下文附加到片段上下文。

What lifecycle will be perform on dialog open or moving from one activity to another?? 在打开对话框或从一个活动转移到另一个活动时将执行什么生命周期?

Read here more. 在这里阅读更多。

https://developer.android.com/reference/android/app/Activity.html https://developer.android.com/reference/android/app/Activity.html

Not all, only methods you thing is essential for your task. 并非全部,只有您所用的方法对您的任务至关重要。 see docs on Activity's lifecycle: https://developer.android.com/reference/android/app/Activity.html 请参阅有关Activity生命周期的文档: https : //developer.android.com/reference/android/app/Activity.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM