Fragments in Android

Naved shaikh
2 min readJan 1, 2021

What is Fragment in Android?

Fragment is like the part of Activity. It is also know as a sub-activity. An Activity can display one or more on the screen at the same time. Fragments represent multiple screen in one Activity.

Each Fragment has its own lifecycle that is affected by Activity lifecycle methods because fragments are embedded in Activity.

You can add or remove Fragment while the Activity is running. Fragment was added in Android API level 11 which is Honeycomb version.

Fragment Manager class is responsible to make interaction between fragment objects.

diagram of fragment lifecycle

Android Fragment Lifecycle Methods

Fragment has 12 lifecycle method :

  • onAttach() : called only once when it is attached with activity.
  • onCreate() : is used to initialize the fragment.
  • onCreateView() : creates and returns the view hierarchy.
  • onActivityCreated : it is invoked after the completion of onCreate method.
  • onViewStateRestored() : It provides information to the fragment that all the saved state of fragment view hierarchy has been restored.
  • onStart() : makes the fragment visibile.
  • onResume() : makes the fragment interactive.
  • onPause() : is called when fragment is longer interactive.
  • onStop() : is called when fragment is no longer visible.
  • onDestroyView() : allow the fragment to clean up resources.
  • onDestroy() : allow the fragment to do final clean up of fragment state.
  • onDetach() : it is called immediately prior to the fragment no longer being associated with its activity.

How Create Android Fragment

Fragment can be created in two ways static and dynamically.

Steps to incorporate fragment

Static Fragment:

  1. Create fragment layout xml file.
  2. Create fragment (by extending fragment class).
  3. Set the fragment layout xml file to fragment.
  4. Use fragment tag to include fragment in layout xml file.

Dynamic Fragment:

  1. First 3 Steps will same as of Static Fragment
  2. Add a layout in xml file that will host a fragment
  3. write a code to add a fragment to activity

For more info visit : https://developer.android.com/guide/fragments/lifecycle

--

--