Fragments are very important components of user interface in android apps. They were introduced first in Android 3.0 (Honeycomb) API.
Understanding design paradigm of Fragments
Fragments were introduced for primarily supporting modular and flexible UI on large screen devices such as tablets.
Fragments are managed by an activity. Usually each fragment represents a portion of a screen. There can be more than one fragment in an activity. Fragments may also be called sub-activities. When you add a fragment as a part of your activity layout, it lives in a ViewGroup inside the activity's view hierarchy and the fragment defines its own view layout.
LIFECYCLE
Just like an activities, fragments also have a lifecycle. A fragment gets notified for following events.
- Get attached to activity - onAttach(Activity)
- Create fragment - onCreate(Bundle)
- Create View - onCreateView(LayoutInflater, ViewGroup, Bundle)
- Activity creation - onActivityCreated(Bundle)
- View state restored - onViewStateRestored(Bundle)
- Made visible to user - onStart()
- start of user interaction - onResume()
- pause of user interaction - onPause()
- Made invisible to user - onStop()
- On view destruction - onDestroyView()
- Destroy fragment - onDestroy()
- Get detached from an activity - onDetach()
As a programmer, you should override various lifecycle callback methods, typically we implement onCreate(), onCreateView() and onPause() methods.
Subclasses of Fragment
- DialogFragment - For displaying the floating dialog
- ListFragment - For displaying list of items
- PreferenceFragment - Useful for creating settings activity
References
- https://developer.android.com/guide/components/fragments.html
- https://developer.android.com/reference/android/app/Fragment.html