The Need

Chances are that the first class you learned to use when you became an Android developer was the Activity class.

After all, the Activity class provided your app with a user interface. By organizing your user interface components on an activity, the activity became the canvas on which you were painting your application masterpiece.

[Early Days]
In the early days of Android, building an application’s UI directly within an activity worked reasonably well. A majority of early applications had a relatively simple user interface, and the number of different Android device form factors was small. In most cases, with the help of a few layout resources, a single activity worked fine across different device form factors.

[Present Scenario]
Today, Android devices come in a wide variety of form factors with incredible variation in their sizes and shapes. When you combine this with the highly interactive user interfaces of modern Android applications, the creation of a single activity that effectively manages the user interface across such divergent form factors becomes extremely difficult.

[One possible solution – Not a better way]
One possible solution is to define one activity to provide the user experience for a subset of device form factors—for example, smartphones. Then, we can define another activity for a different subset of form factors, such as tablets.

[The Problem]
The problem with this approach is that activities tend to have a lot of responsibilities beyond simply rendering the user interface. With multiple activities performing essentially the same tasks, we must either duplicate the logic within each of the activities or increase the complexity of our program by finding ways to share the logic across activities, such as creating potentially complex inheritance relationships.

The approach of using different activities for different form factors also substantially increases the number of activities in the program, easily doubling or tripling the number of activities required. In addition, the advent of Google’s material design specification further increases the complexity of the code contained within each activity.

[Better Solution – UI Modularization]
We need a better solution, one that allows us to modularize our application’s user interface into sections that we can arrange as needed within an activity; fragments are the solution.

Android fragments allow us to partition the UI into functional groupings of user interface components and logic.

——->
An activity can load and arrange the fragments as needed for a given device form factor.

fragment3