Architecture of Mobile Applications

1. Definition and Importance

1.11. Fragments

2. Fragments

Definition

A Fragment represents a portion of an activity that can be reused across multiple activities. Fragments are modular UI components that allow for flexible and dynamic user interfaces. Fragments are reusable components that represent a portion of an Activity's UI. They can be dynamically added, removed, or replaced within an Activity. Think of them as mini-Activities that live inside a larger Activity.

Key Characteristics

  • Fragments must be hosted inside an activity.
  • They have their own lifecycle, which is closely tied to the activity they belong to.
  • Fragments can be added, removed, or replaced dynamically.
  • They promote reusability, especially in tablet or multi-pane UIs.

Benefits

Modularity: Fragments allow you to break down complex UIs into smaller, more manageable pieces.

Reusability: Fragments can be reused across different Activities or even within the same Activity.

Dynamic UI: Fragments can be added or removed at runtime, allowing you to create flexible and adaptive UIs.

Tablet Support: Fragments are essential for creating UIs that adapt well to different screen sizes, especially on tablets. You might have a two-pane layout on a tablet, where one pane displays a list of items (one Fragment) and the other pane displays the details of the selected item (another Fragment).

Fragment Lifecycle

Fragments follow a lifecycle similar to activities, but with additional states:

  1. onAttach(): Called when the fragment is attached to an activity.
  2. onCreateView(): Creates and returns the fragment’s UI view.
  3. onActivityCreated(): Called when the activity’s onCreate() is completed.
onStart(), onResume(), onPause(), onStop(), onDestroy(), and onDetach() are similar to activity lifecycle methods.