Activity是一个用户界面组件,主要用于构建应用程序的单个屏幕,代表屏幕上的主要关注点。一项活动一次可以承载一个或多个片段。 Fragment ,随着平板电脑出现更大的屏幕,是附加到活动中并在活动中显示的可重用组件。它基本上是一个活动的一部分,可以实现更模块化的活动设计。我们可以称一个片段是一种子活动。它总是由一个活动主办。它有自己的布局和自己的行为,以及自己的生命周期回调。我们可以在活动运行时添加或删除活动中的片段。可以只使用活动开发 UI,但这通常是一个坏主意,因为它们的代码以后不能在其他活动中重用,并且不能支持多屏幕。 Activity是应用程序的 UI,用户可以通过它进行交互,而 Fragment 是 Activity 的一部分,它是 Activity 内部的子 Activity,它有自己的生命周期,与活动生命周期并行运行。
活动生命周期
要了解更多信息,请参阅Android 中的 Activity Lifecycle with Demo App 。
片段生命周期
要阅读更多信息,请参阅Android 中的 Fragment Lifecycle
差异表
Activity |
Fragment |
---|---|
Activity is an application component that gives a user interface where the user can interact. | The fragment is only part of an activity, it basically contributes its UI to that activity. |
Activity is not dependent on fragment | Fragment is dependent on activity. It can’t exist independently. |
we need to mention all activity it in the manifest.xml file | Fragment is not required to mention in the manifest file |
We can’t create multi-screen UI without using fragment in an activity, | After using multiple fragments in a single activity, we can create a multi-screen UI. |
Activity can exist without a Fragment | Fragment cannot be used without an Activity. |
Creating a project using only Activity then it’s difficult to manage | While Using fragments in the project, the project structure will be good and we can handle it easily. |
Lifecycle methods are hosted by OS. The activity has its own life cycle. | Lifecycle methods in fragments are hosted by hosting the activity. |
Activity is not lite weight. | The fragment is the lite weight. |
想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!