As the name suggests, a fragment is a subset of the UI in an
activity. What this means is now you can
create multiple fragments in the same UI of an activity. The fragment can
perform actions independent of other fragments while an activity is running. This
means a fragment has its own lifecycle and it exists till the activity is
running. The fragments can also be reused. This property is released from
Android 3.0 API 11 onwards but it can be used in lower version as well, refer
to this to get more info.
So what
is the use of fragments, well there are lot of places where these properties
can be exploited to the fullest. A developer can create 2 separate fragments
where in one fragment can be used to display a list of values and other
fragment can be used to display description of the item selected in the list. Developers
can also take advantage of this in devices like tablets where the display area
is very large and by using fragments they can add many functionality in a single
activity.
LifeCycle on a
Fragment –
In this
lets see how to use a fragment. The following are the states while you use a
fragment.
Creation of Fragment – You need to create a subclass of
Fragments. Then you need to attach the fragment to an activity using Attach().
Then you need to call the view hierarchy with which the fragments are
associated with using creatView() method.
Then you need to create onCreate() where in you instantiate the fragment
and retain the parts of the fragment when it is paused state.
Running state of a fragment- When the activity is started
the onStart() method is called by the activity to make the fragment visible to
user.
Resume – The method
onResume() makes the fragment intractable with the user.
Paused – In this state the fragment is processing function
after the user action or has been paused. This is done by onPause() method.
Stop – When the activity is completed or closed by the user the
method onStop() is called.
Destruction of the fragment – The method onDestroyView() is
called to destroy the view hierarchy associated with the fragment. Then it
calls onDestroy() to release all the resources used by the fragment. Then the
fragment is disassociated from the activity by the method onDettach().
As you can see it’s relatively complex but none the less
interesting and helpful in using the screen real estate and providing a nice UI
to the users. In the next post will give an example using the fragment.