Fragments – Android Dynamic Design Layout.

Fragments are part of Activity in Android. Fragments have their own UI. An activity can have multiple Fragments. A single fragment can be reused in multiple Activities. Fragment helps in designing more dynamic Activity.

The fragment is always hosted inside an Activity, therefore its lifecycle is also dependent on Activity. Whenever Activity is paused or destroyed, all fragments inside Activity are paused or destroyed.

When you add Fragment in Activity, it stays in ViewGroup inside Activity’s View hierarchy. Fragment has its own view layout.

Dynamic Design Layout

Fragments were introduced in Android 3.0 (Honeycomb). Its main purpose to create dynamic layouts on large screen devices such as tablets. Fragments should be designed as a modular and reusable component because it can be used by multiple Activities. Fragment liabrary enables applications to provide layouts depending upon screen types and sizes.

Fragment Creation

Programmatically, Fragments can be created by subclassing Fragment class provided by Android. It has callback methods,

  • onCreate()
  • onStart()
  • onPause()
  • onStop()

Fragment Life Cycle

Android Fragments has life cycle similar to Activity life cycle. A Fragment can exist in three states.

  • Resumed – Activity is running and Fragment is visible in the Activity.
  • Paused – Focus is with another Activity but Activity in which Fragment is there is still visible.
  • Stopped – The Activity in which Fragment is hosted is stopped or it has removed Fragment.

The major difference between Activity life cycle and Fragment life cycle is the way in which they are stored in back stack. By default,an activity is placed in back stack of activities where as fragment is placed in back stack by host activity.

Fragment Coordinating with Activity Life Cycle

Since Fragments reside in Activity, its lifecycle directly affects the Life Cycle of Fragments. Each life cycle callback for Activity also results into the similar call back for Fragments. So, if Activity receives life cycle callback onPause(), Fragment also receives the same callback method. Fragments has few more callback methods apart from standard methods, they are,

  • onAttach() – This is called when Fragment is associated with Activity.
  • onCreateView() – This is called to create view hierarchy in Fragment.
  • onActivityCreated() – This is called when host Activity is created.
  • onDestroyView() – This is called when Fragment view hierarchy is removed.
  • onDetach() – This is called when Fragment is disassociated with host Activity.

Fragment Types

  • DialogFragment – This displays a floating dialog.
  • ListFragment – Displays list of items. List is managed by Adapter which can be customised
  • PreferenceFragmentCompat – This Displays a hierarchy of Preference objects as a list.

For more expertise, please contact Purplechai.

Leave a Reply

Your email address will not be published. Required fields are marked *