I am learning Android programming and right now and i'm reading about fragments. I understand what fragments are, but either the tutorial is missing some steps or i'm missing something. So my question is when developing an Android UI, what are the benefits, if any, to using fragments as apposed to single page layouts? Are fragments more common than single page layouts or is it more based on the situation. Also, if fragments are more common, do you try to structure most situations so that fragments work?
-
1*A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).* -- http://developer.android.com/guide/components/fragments.html – Robert Harvey Jun 05 '13 at 15:53
-
Thanks, I understand what they are. What im getting at are what the benefits, if there are any, over single page layouts in the real world. I will update my question. – DFord Jun 05 '13 at 15:56
2 Answers
Fragments aren't terribly useful on a phone. They were added to the API when people started wanting easier ways to take advantage of the extra real estate on a tablet.
Think of an app with a list down the left side. When you select an item on the list, it launches a new activity using the remainder of the screen space, and you want to be able to swipe to cycle between previously selected activities.
Without fragments, you require a class to manage the entire screen, keep a stack of which activities have been selected, keep track of which one is current, and manage all of their life cycles. If you use the same app on a phone, where the activity takes the entire screen, you don't need the manager class. With fragments, all the life cycle stuff is handled for you, essentially moving your manager class into the operating system. That makes tablet development easier and more standardized, and also makes sharing code between phones and tablets easier.

- 146,727
- 38
- 279
- 479
The benefit is reuse. You can reuse a fragment in different activities, just like the documentation says.
Imagine an address block on an invoice and a packing list. The invoice and the packing list are two different activities. With a fragment, you can write the address block once, and use it in both activities.

- 198,589
- 55
- 464
- 673