

When you perform such a fragment transaction, you can also add it to a back stack that’s managed by the activity-each back stack entry in the activity is a record of the fragment transaction that occurred. However, while an activity is running (it is in the resumed life-cycle state), you can manipulate each fragment independently, such as add or remove them. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments. You can think of a fragment as a modular section of an activity, which has its own life-cycle, 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).Ī fragment must always be embedded in an activity and the fragment’s life-cycle is directly affected by the host activity’s life-cycle. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. To put it technically, in Google’s words:Ī Fragment represents a behaviour or a portion of user interface in an Activity. Basically, it is a standardised way for Android to implement Responsive Design. in landscape mode, maybe “list” and “detail” can sit side by side, but in portrait mode, only one can be displayed. Basically, it provides a very neat way for applications to handle a variety of screen sizes and interfaces, but maintain a common codebase.įragments A, B, and C can be combined or separated as appropriate – perhaps changing as the user changes the orientation of the device. Fragments help serve this purpose in Android.Ī self-contained unit of functionality can be implemented in a Fragment and reused in multiple places without the need for duplication.

Programmers are always encouraged to re-use code and always avoid, if possible, duplicating code. But when you view the same app on a tablet the list of recent emails is accompanied, on the right, by the content of one particular email, previewed in its own sub-area of the screen. Perhaps, for example, the index of most recent emails is one Fragment. It represents a portion of logic as displayed on the screen. Well, a Fragment can be thought of as a sub-component of an Activity.
