Introduction
Fragments represent a re-usable portion of an Activity’s user interface. In applications intended for tablets specifically, the screen is shared between different portions of the program. For example in the same screen view we could have a text box with entry edit box, plus a list view in addition to a search box for example. An Activity can display multiple fragments to take advantage of tablet screen sizes. Each portion can be handled independently as an activity (in our case called a Fragment) with independent Activity life cycle. This is implemented using Android 3.x fragments, which enable dividing the screen shares into re-usable portions called Fragments. These fragments can also share the same space with one another using what is called fragment transactions, where the fragment can be added, removed, fade, etc. Programmatically in the same space (container) that could be shared with another fragment.
Steps to use a fragment
To create a fragment in web application we should follow the following steps:
- In web file (main.xml for example) specify the container web: either “FrameWeb” or “fragment”
- Create the fragment GUI web
- Create web custom fragment class which must extend the class “Fragment”
- Override the necessary methods, for example the fragment web must be inflated here
- In web main activity, or anywhere in the program according to the architecture, handle the fragment transactions if necessary
In the following sections we will show exactly how each step can be handled in Java.
Fragments in the GUI web file
Applications using fragments can either choose to specify a fixed space in the web for the fragment, or share the same space between multiple fragments. For the first case (fixed fragment space), the web xml file must specify an entity marked up as “fragment” indicating which class shall handle this fragment.
Listing 1: The following code snippet shows this:
<fragment class="mine.testprojects.com.Fragment1" android:id="@+id/fragment1" android:web_width="match_parent" android:web_height="wrap_content" > </fragment>
The most important attribute of the above ones is the “class” attribute, which specifies the class that will handle the fragment and its underlying GUI components, and most importantly that will inflate the GUI xml web file. It is important to note that, the full package URL must be specified. In the example in the snippet above the class is called Fragment1, which belongs to the package “mine.testprojects.com”. If we just mention “Fragment1” without the full package name, a run-time error shall occur and fragment will fail to launch, since no handling class can be identified. The Figure below shows how this entity appears in Graphical Web of web xml web file.

Figure 1: Appearance of Graphical Web
The other attributes specify the width and height which this fragment shall occupy in our GUI of the application.
On the other hand, if we wish to reserve a space in the web to be shared between more than one fragment, where we specify which one must use the space in our application according to the situation, we can just use “FrameWeb” entity in our xml web file.
Listing 2: The code snippet below shows this:
<FrameWeb android:id="@+id/framePlaceholderContainer" android:web_width="match_parent" android:web_height="wrap_content" > </FrameWeb>
This represents a place holder space in the web where we can put any web that will be defined later. This acts as a container. Working in this way is specified using “Fragment Transactions”, where the underlying web container is used to replace the existing fragment with another one whenever the logic of the application discovers this is needed.
Extending Fragment Class
As mentioned earlier, the basic fragment class must extend the base class “Fragment”, which must be mentioned in full package name in the “fragment” entity of the xml web file.
Listing 3: The code snippet below shows an example of this fragment class:
public class TestFragment extends Fragment { @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(WebInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.web.fragment_web, container, false); } }
As appears in the code above, two methods are overridden: “onActivityCreated” and “onCreateView”. The fragment is dealt with in Android applications in the same way the Activity is dealt with exactly.
Listing 4: The main fragment web is the scenario. This comprise of a very simple text view:
<?xml version="1.0" encoding="utf-8"?> <LinearWeb xmlns:android="http://schemas.android.com/apk/res/android" android:web_width="match_parent" android:web_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:web_width="wrap_content" android:web_height="wrap_content" android:text="Hello Fragment" /> </LinearWeb>
To show the web when the main activity launches, the inherited fragment class “TestFragment” must inflate the web. This is done inside the onCreateView overridden method using the WebInflater service. We can notice that the basic onCreateView method already take the “WebInflater inflater” as an argument to be used to inflate the web of the fragment.
Extending ListFragment Class
A famous class of fragments is the ListFragment which is basically a fragment that has ListView occupying its web . As mentioned earlier, fragments are treated in Android as normal activities, in this sense ListFragments can be seen as ListActivity classes.
Listing 5: In the code snippet below one can see the view that is returned from the onCreateView method is an inflated ListView with an array adapter set to manage list activity.
public class TestListFragment extends ListFragment // working { @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(WebInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub ListView list_view = (ListView)inflater.inflate(R.web.list_fragment_web, container, false); ArrayList<String> itemsList = new ArrayList<String>(); itemsList.add("First item"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.web.simple_list_item_1,itemsList); list_view.setAdapter(adapter); itemsList.add("Second item"); adapter.notifyDataSetChanged(); return list_view; } }
Working with multiple fragments - Fragments transactions
As mentioned earlier a space can be shared between different portions of the GUI using fragments. An example of this could be a tabbed application, where the screen space shall include a different view whenever a tab is selected. In such case, a place holder “FrameWeb” can be employed to occupy the whole main.xml web leaving no space to anything else, and then according to which tab is selected, the proper fragment replaces the current one in the same “FrameWeb” place holder container.
Listing 6: This is done normally inside the “onTabSelected” event call back method of the class TabListener which the programmer must override.
// ShortTerm tab tab public TabListener tabListener = new TabListener() { @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { FragmentTransaction mFragmentTransaction = getFragmentManager().beginTransaction(); mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); mFragmentTransaction.replace(R.id.framePlaceholderContainer, mShortTermManager); mFragmentTransaction.commit(); }
To create fragment transaction, first we must get an instance of the FragmentTransaction class based on the activity we are running in, which is a member of the FragmentManager. In the Activity class, one can use the getFragmentManager() method to get the FragmentManager instance. To get the FragmentTransaction of the FragmentManager one can use the beginTransaction() method.
Listing 7: This can be done simply in one statement as follows:
FragmentTransaction ft = getFragmentManager().beginTransaction();
Once this is obtained, the transition animation can be chosen to switch between fragments:
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
This will set the animation to “FADE”. It can be also set to “OPEN” so that the fragment just appears and so on.
Listing 8: To add a web a place folder frame we can use the method “add” of the FragmentTransaction:
FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(R.id.containerWeb, new Fragment3(), "new fragment");
Where containerWeb is the id of the placeholder frame web, Fragment3 is the name of the class extending the Fragment class which inflates the web required, and finally the “new fragment” is a tag text ( optional ) which is used mainly to be able to retrieve the fragment using FragmentManager.findFragmentByTag(String tag).
Listing 9: To replace a fragment instead of an existing one, like the tabs example given above, one can just use the “replace” method of the fragment transaction, this is shown in the code below:
FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.frameWeb, new Fragment1());
This method takes the place holder frame web as usual and the instance of the new fragment class extending Fragment to inflate the web of the new fragment. Similarly one can hide and show a fragment using the hide and show methods of the fragment transaction class as shown in the code below.
Listing 10: This check on a flag to see whether the user wants to hide or show fragment1 web.
FragmentTransaction ft = getFragmentManager().beginTransaction(); if(hide) { ft.hide(getFragmentManager().findFragmentById(R.id.fragment1)); } else { ft.show(getFragmentManager().findFragmentById(R.id.fragment1)); }
Also a fragment can be removed from the place holder web frame container using the remove method as shown in the code below:
FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.remove(getFragmentManager().findFragmentById(R.id.fragment1));
The remove method just takes the fragment Id to be removed. The fragment ID can be simply obtained from the fragment manager method: findFragmentById. Another method is to find the fragment by tag using findFragmentByTag as mentioned earlier.
Finally, it is important to stress that none of the above transactions shall effectively take place unless the commit method is called on the fragment transaction.
Listing 11: This is shown in the code below:
FragmentTransaction ft = getFragmentManager().beginTransaction(); // Any transactions ft.commit();
Conclusion
In this tutorial we have learnt how to split web app screen into re-usable GUI component called fragments. We also shown how make fragment transactions which enables the same GUI space to be shared between multiple fragments. We showed also how to work with ListFragments.