4 reasons to use Android Fragments
- select the contributor at the end of the page -
Although Fragments have been part of the Android API for nearly three years, I find that developers still often struggle to understand their value and purpose. A common explanation of Fragments, and one I sometimes even use myself, is:
Fragments group user interface components and their associated logic.That explanation is accurate. However, if someone is struggling with how to apply Fragments in a practical sense, that explanation is about as useful as teaching someone how to tell time by explaining the finer details of Swiss watch construction … sometimes you just want to know what time it is. So in the spirit of just wanting to know what time it is, here are four places where Fragments prove useful.
1. Dealing with device form-factor differencesThe Activity class is often thought of as the main UI class in Android. It is true that Activities do render the UI for an application but Activities also have a lot of other responsibilities such as lifecycle management, platform interaction, etc. Putting all of this burden within the Activity class creates difficulties in dealing with device form factor differences. Ultimately one of two things happen.
- A single Activity has to provide a lot of special case handling for various form factors
- A separate Activity is created for each form factor with the non-UI details duplicated or otherwise shared across each Activity
2. Passing information between app screensHistorically each screen in an Android app was implemented as a separate Activity. This creates a challenge in passing information between screens because the Android Intent mechanism does not allow passing a reference type (i.e. object) directly between Activities. Instead the object must be serialized or a globally accessible reference made available. By making each screen a separate Fragment, this data passing headache is completely avoided. Fragments always exist within the context of a given Activity and can always access that Activity. By storing the information of interest within the Activity, the Fragment for each screen can simply access the object reference through the Activity.
3. User interface organizationTwo of the most common UI metaphors for organizing application screens are Tabs and Dropdown Lists. Tabs are great when there are just a few screens and Dropdown Lists work well when there are several, as when selecting a folder from the Android email app as shown here.
- Tabs use ActionBar.NAVIGATION_MODE_TABS and ActionBar.TabListener
- Dropdown Lists use ActionBar.NAVIGATION_MODE_LIST and ActionBar.OnNavigationListener