Before we get into differences between activity and fragment let's see what is activity and what is a fragment. The short answer both of them are simple screens to place elements in them. If you are a web developer consider activity and fragment as document and div.
Let's dive into the difference
- Activity is an application component that gives a user interface where the user can interact with your application, whereas fragment is part of your activity embedded into it and has its UI with its elements.
- App has to have activity but it's not the case with the fragment and it can have any number of fragments.
- Fragment appears in a part of activity hence it is dependent on activity.
- Fragments help us to create multi-pane UI. (e.g we have three screens
tabson the main screen
Statusits a good example of 3 fragments on activity)
- Fragments also helps us to create different UI in the different orientation of screen
verticle(e.g g-mail app in tablet devices
verticleshows a list of emails
horizontalshown list with and opened email) this is possible with the help of fragments
- Lifecycle methods are hosted by OS. Activity has its own lifecycle but fragments are hosted by hosting activity.
- Every activity should be mentioned in the manifest file but it's not the case with fragments
- Activity is heavyweight and fragment is lite weight.
Lifecycle of Activity
Lifecycle of Fragment
By now you should have a good idea about activity and fragment and what is the difference between those two. if you have any doubt drop a comment or contact me on my social media. I'm trying my best to share my knowledge and make android learning easy and fun. If you find it useful please drop like follow me to get the next article updates and share this article as much as you can.