Pages

Monday, December 31, 2012

Using Fragments in Android - A Beginner's Tutorial


Fragments are a great tool in any Android developer's toolkit. They allow for wonderful modularity, while also providing a fantastic way to easily extend your Android application to devices other than phones, such as tablets or televisions.

I will be demonstrating how to implement a fragment in code in your Android application using the ActionBarSherlock library, so you will also be able to use this on pre-Honeycomb devices.

Using Fragments in Code

We are going to need to do 3 things in order to use fragments:
  • Create a fragment layout in XML
  • Create a fragment class
  • Create an activity and add the fragment to this activity
To get started though, we must import ActionBarSherlock. I will not give instructions on this, however it is not too difficult - just follow the instructions given on the library's website.

Once this is done, we will begin designing the fragment like any other activity: using an XML layout!

Our example fragment won't be anything special, only a simple "hello, world" textview:



As you can see, it looks like any other activity or view layout that we may choose to make for our application. Using it in code is almost just as easy, too!

We must create an class for the fragment. Note that we will extend SherlockFragment, but if you are only targeting Honeycomb and up, feel free to use Fragment instead:


Very simple. All it does is inflate the fragment's view, and return it when it's needed.

Finally, we need to create the containing activity. I will assume that your activity is based on an XML file with a layout whose ID is "fragment_container":

As with the last example, we will be extending SherlockFragmentActivity, but feel free to just extend only Activity on Honeycomb and up devices:

 And that is basically all that is needed for an introduction to fragments! If you would like me to go further in-depth, please go ahead and sound off in the comments.

4 comments:

  1. Thank you for writing up this tutorial, but could you explain the XML file whose layout id is fragment_container? I tried to add it myself, but I'm having some trouble.

    ReplyDelete
    Replies
    1. Post updated with example :)

      Delete
    2. Thanks! Hmm, which add method do you use for the FragmentTransaction object? I'm getting the following error:

      fragment_container cannot be resolved to a variable."

      I'm using the add method that accepts an integer and a fragment.

      Is a step missing? If you are using the layout id for the Fragment Transaction, wouldn't you need to use something like R.id.fragment_container? However, you wouldn't be able to do that given the arguments for the add method.

      Delete
    3. Hi you need to change it to ft.add(R.id.fragment_container, mFrag).commit();

      Works great!

      Delete