Difference between Activity and Fragment

Difference between Activity and Fragment

Intro

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 tabs on the main screen Chat, Calls, Status its a good example of 3 fragments on activity)
  • Fragments also helps us to create different UI in the different orientation of screen horizontal or verticle (e.g g-mail app in tablet devices verticle shows a list of emails horizontal shown 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

activity_lifecycle.png

Lifecycle of Fragment

fragment-view-lifecycle.png

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.

Did you find this article valuable?

Support Rishabh Kumar by becoming a sponsor. Any amount is appreciated!