Although fragments were introduced with Android 3.0, they are now available for small screen devices with Android Ice Cream Sandwich. This chapter will cover the basics of fragments and how to use them.
The topics covered in this chapter are as follows:
Fragment is a modular component in an activity which has its own life cycle and event handling, and it is very similar to an activity. Although fragments have their own life cycle, they are directly affected by their owner activity's life cycle. For instance, if an activity is destroyed, its fragments are also destroyed. Every fragment should have an owner activity. A fragment could be added to or removed from an activity dynamically.
Fragments increase software reusability and provide flexibility in user interface design. A fragment could be used by more than one activity. This way you implement once and use multiple times. Furthermore, it is possible to use a fragment for different layout configurations and different screen modes. This way it provides flexibility in user interface design.
Fragments have their own lifecycle; however, they are still directly affected by their owner activity's lifecycle. The following diagram shows the creation flow of lifecycle of a fragment:
The blocks in the diagram perform the following tasks:
onAttach():
When a fragment is added to an activity, the onAttach()
method is called.onCreate():
This method is called when a fragment is created.onCreateView():
This method returns a view. This view is the user interface of the fragment. If the fragment is doing background works and doesn't have a user interface, then this method should return null.onActivityCreated():
This method is called after the owner activity is created.onStart():
After this method is called, the fragment's view becomes visible to the user.onResume()
: After this method is called, the fragment becomes active and the user can interact with the fragment. This method could be called more than once, because this method is called after the application is restarted or paused.The following diagram shows the destruction flow of the life cycle of a fragment:
The blocks in the diagram perform the following tasks:
onPause():
This method is called when the fragment is paused and no longer interacts with the user.onStop():
This method is called when the fragment is stopped. The fragment is not visible to the user after this method is called.onDestroyView():
This method is called when the view of the fragment is destroyed.onDestroy():
This method is called when the fragment is no longer in use.onDetach()
: This method is called when the fragment is removed from the activity.44.220.184.63