Why use Fragments? [duplicate]

The main reason is that fragments are more reusable than custom views.

Sometimes you can’t create a fully encapsulated UI component relying on views alone. This is because there are things you would want to put into your view but can’t because only an Activity can handle them, thus forcing tight coupling between an Activity and a View.

Here is one such example. Lets say you want to create a reusable UI component that, among many things, want to capture a photo and do something with it. Traditionally you would fire an intent that starts the camera and returns with the captured image.

Notice that your custom UI component can’t fully encapsulate this functionality because it will have to rely on hosting Activity’s startActivityForResult because views don’t accept activity results (they can indirectly fire an intent through context).

Now if you wanted to reuse your custom UI component in different activities you would be repeating the code for Activity.startActivityForResult.

Fragment on the other hand cleanly solve this problem.

Similarly your fragment can contribute items to your options menu, something traditionally only an Activity could do. Again this could be important if the state of your custom view dictates what goes in the menu.

Leave a Comment