Android Fragments

In this tutorial you will learn about the Android Fragments and its application with practical example.

Fragment is a part of Activity or also we can say sub activity. It represent multiple screen inside an activity.

The fragment’s lifecycle is affected by the host activity’s lifecycle, For example if host activity is in pause status so all fragment will be in pause status and if activity is destroyed so all fragment will be destroyed.

For creating an Fragment you need to extend through Fragment class or in other words you need to create subclass of Fragment. As I told you before that fragment is a part of activity or sub activity so Fragment class has code that looks like an Activity. It contains callback methods like an activity, like onCreate(), onStart(), onPause() and onStop(). You can understand lifecycle of Fragment from below Image.

fragment_lifecycle

 

  1. onAttach() : It calls when Fragment attach with an Activity, onAttach() method is called only once.
  2. onCreate() : It calls when creating Fragment. It is used to initialize essential components of fragment.

3.onCreateView() : It is called by the system for drawing User Interface for Fragment. For drawing UI for fragment , you need to return a View that is the root of fragment’s layout.

  1. onActivityCreated() : It is called after onCreateView() method when the host activity is created.

5.onStart() : It makes fragment visible.

  1. onResume() : It makes fragment active.

7.onPause() : The system calls this method when fragment is no longer active. First indication of this method is that user is leaving the fragment it does not mean that fragment is being destroyed.

8.onStop() : It is called when the fragment is no longer visible.

9.onDestroyView() : this method allows the fragment to clean up resources.

10.onDestroy() : this method allows the fragment to do final clean up of fragment state.

  1. onDetach() : It is called when the fragment is no longer associate with host activity.

Types of Fragment : Single Frame Fragment , List Fragment, Fragment Transaction.

In below code you will get information about Fragment creation.

frag

In this tutorial we have learn about the Android Fragments and its application with practical example. I hope you will like this tutorial.