Difference Between a Fragment and an Activity in Android
An Activity is a user interface component that is mainly used to construct a single screen of the application and represents the main focus of attention on a screen. An activity can host one or more fragments at a time. Fragments, as tablets emerged with larger screens, are reusable components that are attached to and displayed within activities. It is basically a piece of an activity that enables more modular activity design. We can call a fragment is a kind of sub-activity. It is always hosted by an activity. It has its own layout and its own behavior with its own life cycle callbacks. We can add or remove fragments in an activity while the activity is running. It is possible to develop a UI only using Activities, but this is generally a bad idea since their code cannot later be reused within other Activities, and cannot support multiple screens. Activity is the UI of an application through which user can interact and Fragment is the part of the Activity, it is a sub-Activity inside activity which has its own Life Cycle which runs parallel to the Activities Life Cycle.
To read more refer to Activity Lifecycle in Android with Demo App.
To read more refer to Fragment Lifecycle in Android
|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.|