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?
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
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.
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.