July 14, 2014

Using Fragments

Fragments were added to Android 3.0 to better support user interfaces for devices with 
large screens, such as tablets. Every fragment needs a host activity and a single fragment can span across multiple activities. The fragment by itself has several life-cycle methods as shown below,

There are two ways to load a fragment into an activity
1)Declare it statically using the using the Activity's layout file 
2)Add it programmatically using the FragmentManager

Static Fragment:

Define the fragments to be hosted in the current activity using the activity layout file as shown below,
Now when the activity is loaded. The corresponding fragments are attached and the life-cycle methods  of both fragments are invoked. Once the fragments are loaded as defined statistically in the above xml, the view of fragment is loaded in onCreateView(). 

TitlesFragment is the one which inherits the ListFragment class and thereby all list related actions such as setting the Single choice mode can be done in the onActivityCreated() as shown below.
Another point to note here is that a ListSelectionListener interface is defined here which needs to be implemented in the hosting activity. This is done typically in any fragment scenario because the hosting activity has reference to both the fragments and can control the data shown in a fragment different from the fragment from which the selection was done. The activity typically acts like the Orchestra conductor by implementing the ListSelectionListener's onListSelection() method as shown below,
The TitleFragment's onListItemClick hook method call this onListSelection method as shown below
Thus the corresponding details of the clicked title  is displayed in the textview of the DetailsFragment.

Dynamic Fragment:

Here the activity xml does not define the fragments instead only defines the views which are going to be loaded for the corresponding fragments. So we have to programmatically call the fragments to be hosted in the current activity.

In the activity's onCreate method load the fragments using the fragmentManager as shown below,
In the static fragment example, both fragments were loaded at the same time. Here first the title is loaded and the second fragment is loaded and the entire activity layout is adjusted via a addOnBackChangedListener callback method.
Rest of the fragment implementation is similar to the static example. Examples were referred from Dr.Adam Porter's lectures.

No comments:

Post a Comment