Fragment
A reusable UI component with its own lifecycle
Benefits of using fragments
Reuse a Fragment in more than on Activity
Add or remove dynamically as needed
Integrate a mini-UI within an Activity
Retain data instances after a configuration change
Represent sections of a layout for different screen sizes
Steps to use a fragment
Create a subclass of Fragment
Create a layout for the Fragment
Add Fragment to a host Activity
Statically in layout
Dynamically using fragment transactionsExamples of subclases of Fragment
DialogFragment: Floating dialog (examples: date and time pickers)
ListFragment: List of items managed by adapter
PreferenceFragment: Hierarchy of Preference objects (useful for Settings)
Add a Fragment to an Activity
Add statically in Activity layout, visible for entire Activity lifecycle
Add (or remove) dynamically as needed during Activity lifecycle using Fragment transactions
Add a Fragment dynamically
Specify ViewGroup for Fragment in layout
Instantiate the Fragment in Activity
Instantiate FragmentManager
Use getSupportFragmentManager() for compatibility
Use Fragment transactionsFragment operations are wrapped into a transaction:
Start transaction with beginTransaction()
Do all Fragment operations (add, remove, replace, hide, show, addtoBackStack() etc.)
End transaction with commit()
Lifecycle
Lifecycle