Introducing Android Fragments
Written by Mike James   
Thursday, 13 February 2014
Article Index
Introducing Android Fragments
Using a Fragment
The Activity
Summary and Conclusion

Fragments are components of the Android UI. For most beginners, and even more experienced devs, they are a mystifying. However they are very useful and well worth getting to understand. Here we find out exactly what Fragments are all about. While this article is part of our ongoing Android Adventures series about using Android Studio, it applies whatever development environment you are using.  

 

Androidgears

Android Adventures With Android Studio

Contents

  1. Getting Started With Android Studio
  2. The Activity And The UI
  3. Building The UI and a Calculator App
  4. Lifecycle and State
  5. Basic Controls And Events
  6. Spinners
  7. Pickers
  8. UI Graphics A Deep Dive
  9. Introducing Fragments
  10. Fragments and XML
  11. Fragment And Activity Working Together
  12. Managing Fragments
  13. Custom dialogs using DialogFragment
  14. Dialog Classes In DialogFragment

When you first start working with Android it is difficult to see why you should bother with the strange new Fragment object. It really doesn't seem to do anything extra over and above a simple Activity and it adds another layer of complexity.

In addition finding out exactly what a Fragment does for you is very difficult.

Perhaps they are best ignored?

It is true that for many simple apps you really don't need to bother with the extra complexity of using a Fragment. If you are serious about developing an app over a long period of time then it probably is worth starting off by using a Fragment - even if it isn't actually necessary.

This is certainly the attitude that Google would like you to take and in Android Studio even the simplest apps start off using a Fragment.

This is, of course the reason the Simple Blank Activity template was introduced earlier in this book. However now it is time to find out what Fragments are all about and finally understand the standard template among other things.

This is a fairly deep look at using Fragments and it might well tell you more than you want to know on a first reading but if you are going to make use of Fragments properly you do need to know this. 

In this chapter we focus on Fragment basics - creating a Fragment, displaying a Fragment and Fragment event handling. In the next chapter we look at Fragments and XML, the designer, the standard template and using Fragments in devices that run Android version earlier than Honeycomb.  The third chapter on Fragments looks at the problem of managing Fragments to create flexible UIs. 

What Is A Fragment?

A Fragment is like a very cut down Activity. It has a set of events that signal various stages of its lifecycle like an Activity. It also has its own associated View object which defines its UI - but it has no way of displaying that View object. 

To display its View object a Fragment has to pass it on to an Activity. The Activity decides how best to display the Fragment's UI.

The basic idea is that a Fragment is a lot like having a View hierarchy that the Activity can decide to display as it needs.  The idea is that if the device that the application is running on has enough space then Fragments can be displayed on the same screen. If the device is too small you can arrange for each Fragment to be displayed on its own. 

One idea that it is important to dispel as early as possible. This management of Fragments according to screen size is entirely up to the programmer. The system doesn't support any automatic management of Fragments even though there is a class called FragmentManager.

What you do with a Fragment is up to you and it is still a fairly low level mechanism.

In short what you do with a Fragment is entirely up to you.

The key method in using a Fragment is

onCreateView(LayoutInflater inflater,
             ViewGroup container,
             Bundle savedInstanceState)

this returns a single View object, always a ViewGroup, with the set of View object that defines the Fragment's UI. The Activity calls this event handler when it is time for the Fragment to provide its UI for display. 

The Activity passes a LayoutInflater to help the Fragment create the View hierarchy from an XML file, a container that the is the ViewGroups that will contain the fragment's UI and finally a Bundle if the Fragment already exists and has been suspended - much like an Activity.  

It looks as if the Fragment's only role in life is to create a View and this is true but it has more functionality than just a ViewGroup object. The Fragment is also an object that has a lifecycle and persists even when its View hierarchy isn't on display. This makes it easier to arrange for things like the back button and other state changes to be implemented. To make full use of the Fragment you have to know about its lifecycle but for the moment we can simply focus on the onCreateView event.

A Simple Fragment

The best way to understand all this is to find out how Fragments work in detail.

So start a new Simple Blank Activity project and this time make sure you select Honeycomb Android 3.0 for the minimum required SDK - the reason is that Fragments were introduced with this version. The question of supporting Fragments in earlier versions just complicates things - but see the next chapter. 

Creating a Fragment is a matter of deriving your own class from the Fragment class. To do this you can simply right click on the MainActivity class and select New, Java Class from the menu:

 

class

 

Next you have to give the class a suitable name:

 

classname

 

This creates a new file in the project to store the class.  

If you have programmed in other languages it is worth knowing that Java generally expects you to put each new class in its own file.  

Next we need to edit the class to make it inherit from Fragment:

package com.example.app;
import android.app.Fragment;
public class myFragment extends Fragment {

}

If you start typing "extends" Android studio will autocomplete and the same for "Fragment". It will also automatically add the import statement for you.

Now we have to fill in the details of onCreateView.

We could define an XML layout file or use the designer - more of which in the next chapter where we look at using Android Studio's Fragment facilities - but the most direct way and the one that lets you see exactly what is happening is to create the View objects in code.

In practice you would normally use the XML to create the View hierarchy but working with code means there is no irrelevant details to confuse the issue.

If you are not happy with creating View objects in code then see the previous chapter: UI Graphics A Deep Dive

Android Studio will autogenerate a stub for the even handler if you simply start to type onCreateView and select the correct method from the list that appears. It will also automatically add the import statements you need. 

To create a simple UI for the Fragment to supply to the Activity we will just create a LinearLayout containing a Button:

@Override
public View onCreateView(
                   LayoutInflater inflater,
                   ViewGroup container,
                   Bundle savedInstanceState) {
 LinearLayout linLayout=
               new LinearLayout(getActivity());
 Button b = new Button(getActivity());
 b.setText("Hello Button");
 linLayout.addView(b);

 return linLayout;
}

 

This should be perfectly easy to follow but there are a few subtle points. When you create a View object you have to provide it with a "context" - this is the Activity it belongs to and you usually pass it this to indicate the current object i.e. the Activity instance. In this case we are in an instance of the Fragment object so you can't use this.

However at the time that the onCreateView is called the Fragment will be associated with a Activity i.e. the Activity that is going to display its View. You can use the getActivity method to return the Activity that the Fragment is associated with and this is what you use as the context when you create a View object within a Fragment - that is:

Button b = new Button(getActivity());

Notice also that you seem to have to return a ViewGroup object from onCreateView, even though this isn't documented. Finally you don't add the Fragment's View to the container you have been passed. You are only provided with it so you can find out details of the layout and adjust your View objects accordingly.

At this point we have a Fragment that returns a LinearLayout which contains a Button object with the text "Hello Button". Not a very useful Fragment but the simplest example I can think of. 



Last Updated ( Friday, 20 June 2014 )
 
 

   
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.