Android Fragments Overview

Android Fragments provide a mechanism to create modular sections of an Activity. You can see how Fragments fit into the overall Android structure in the blog post Android App Major Elements. You can see an example of Fragment use in the blog post Android Fragments.

Fragments provide a couple of significant benefits for Apps:

  • Fragments facilitate App adaptation to various screen sizes and dimensions. 
  • Fragments have their own life cycle that can be used to implement unique behavior for different App Fragments.

Below is an overview of Fragments and the Android elements they interact with for Fragment control.

Activity (Main)

The main Activity of an app uses the setContentView() method to establish a View.

Activity (for Fragment)

Activities can start and be started by Fragments.

View

The View class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is the base class for widgets, which are used to create interactive UI components (buttons, text fields, etc.). Views can be accessed via their ids or from the Root View.

Root View

The Root View is the base of the tree for all the Views for an app. It can be referenced using android.R.id.content.  

Layout (XML)

Layout XML can be used to define Views. When an app is compiled, the XML definitions are used to create View details. Note that this can include Fragment properties. If a Layout that includes a Fragment specification is used by the Activity setContentView() method, that Fragment will be automatically started by the Android operating system.

Fragment

A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity. Sub classes of Fragment include: PreferenceFragment, DialogFragment and ListFragment.

Fragment Manager

The FragmentManager class is an Interface for interacting with Fragment objects.

Fragment Transaction

The FragmentTransaction class is used for performing Fragment operations.