What is the difference between a fragment and an activity? Explain the relationship between the two. When and why should you use one over the other?

Copied from https://www.toptal.com/android/

An Activity is a user interface component that are mainly used to construct a single screen of application, and represents the main focus of attention on a screen.

In contrast, Fragments, introduced in Honeycomb(3.0) as tablets emerged with larger screens, are reusable components that are attached to and displayed within activities.

Fragments must be hosted by an activity and an activity can host one or more fragments at a time. And a fragment’s lifecycle is directly affected by its host activity’s lifecycle.

While it’s possible to develop a UI only using Activities, this is generally a bad idea since their code cannot later be reused within other Activities, and cannot support multiple screens. In contrast, these are advantages that come with the use of Fragments: optimized experiences based on device size and well-structured, reusable code.

The core ideas behind fragments is that fragments can be hosted in a variety of ways.

  • For example, when you want to implement a list & detail view. If the device is a phone with small size screen, you have to implement list and detail view in different screen; if the device is tablet with large screen, you can show both list and detail on the same screen. Fragments make implementing this functionality easy. The list of emails would exist in one fragment, and the detail view for an email would exist in another fragment. Depending on the device size, our activity will decide to show either one or both of these fragments.

  • Another example, let’s say you want the user to be able to horizontally scroll through a set of pages where each may show a list, photo, photo gallery, dashboard, or form. Here you might use a ViewPager in your Activity whose items are fragments that handle each of those unique user interface functions separately. If the developer had written these pages as Activities, they would have had to refactor them as fragments.