Tuesday, November 25, 2014

Android Fragments

A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity which enable more modular activity design. It will not be wrong if we say, a fragment is a kind of sub-acitivity. Following are important points about fragment:
  • A fragment has its own layout and its own behavior with its own lifecycle callbacks.
  • You can add or remove fragments in an activity while the activity is running.
  • You can combine multiple fragments in a single activity to build a multi-pane UI.
  • A fragment can be used in multiple activities.
  • Fragment life cycle is closely related to the lifecycle of its host activity which means when the activity is paused, all the fragments available in the acivity will also be stopped.
  • A fragment can implement a behavior that has no user interface component.

Fragment Life Cycle

Android fragments have their own life cycle very similar to an android activity. This section briefs different stages of its life cycle.
Phase I: When a fragment gets created, it goes through the following states:
  • onAttach()
  • onCreate()
  • onCreateView()
  • onActivityCreated()

Phase II: When the fragment becomes visible, it goes through these states:
  • onStart()
  • onResume()
Phase III: When the fragment goes into the background mode, it goes through these states:
  • onPaused()
  • onStop()
Phase IV: When the fragment is destroyed, it goes through the following states:
  • onPaused()
  • onStop()
  • onDestroyView()
  • onDestroy()
  • onDetach()