Android Fragments Example

One thing I think is essential for understanding a feature in Android is a working example. The difference between a good write-up and the same write-up with source code attached is huge for me. I fully appreciate the great documentation and resources provided on the Android Developers website and on other websites. However, the working example is usually my guarantee that I will eventually understand a feature.

A case in point for me is the Fragments feature. I have been using them for about a year now so I am getting more comfortable using them in my app work. Several times in that time period, I have started apps with Fragments in Android 4+ and had to rework them so I could support older versions of Android. For me, that’s Android 2.3.3 (API 10). Fortunately, that’s easy to do because of the Android V4 Compatibility package that allows you to use Fragments in the earlier versions.

Since the need keeps coming up for me to have both Fragments and backward compatibility, I decided to build myself a simple demo app that combines both. That demo app helps me remember how to do that. Often, it is my starter kit for a new app. That’s what I am writing up and sharing in this blog post.


Uses for Fragments

If you have not read about Fragments, here’s my version of why they are useful. They make it easier to have UI components that you can use in different ways in your app. Two main uses: (1) handling differences between your app in landscape mode and your app in portrait; (2) handling differences in your UI when running on a tablet.

The following app screenshots illustrate the points. The first is the app on a small device in landscape. Nothing too surprising is going on. If you select a title on the left, the text for that title appears on the right. Reorient to portrait mode and you will see what’s in Figure 2. There is only room for the titles list. When you select a title, the whole screen changes. Titles are hidden and the details appear. The remaining figures show the same app on a tablet. There is more than enough screen in either orientation so the titles are always visible.


Figure 1 – Landscape orientation, small screen


Figure 2 – Portrait orientation, small screen


Figure 3 – Portrait orientation, Nexus 7 tablet, 1280 x 800

How It Works

You have to know only a few things to get this to work:

  1. How fragments can be used to display information in the two situations: standalone activity (Figure 2) and as part of a wider view (Figure 1 or Figure 3).
  2. How to structure your app to support different layouts for portrait and landscape
  3. How to structure your app to support the larger screens of tablets.
  4. How to provide backward compatibility for the Android versions prior to Android 4.

This demo example makes use of the code available with the Fragment class definition. That article explains the first two points above.

For point #3 above, I suggest reading one of my earlier blog posts, “My Dashboard User Interface on Android Tablets“. It explains how to use different layout folders to hold layout xml for different sizes of screens. Two of the most useful references in the References section “New Tools For Managing Screen Sizes”  and “Supporting Multiple Screens“.

The last point in list above has to do with using the new Fragment class in earlier versions of Android. For that, you should read about the V4 compatibility library for Android. Once I had the basic example working, I followed their instructions to make the demo example backward compatible. I did what they described in the section “Using the V4 Library APIs”.

  • Use FragmentActivity as the superclass for you own Activity classes if they are going to use Fragments.
  • When you need a FragmentManager object, call getSupportFragmentManager rather that getFragmentManager.

I did not do anything about the action bar and title bar. They are what they are in each of the Android versions. If you want to read about some options for the action bar, read my note on “Getting Started With Android V4“.

Source Code

You can download the source code for this demo from  the website. Click here: download zip file from The zip is attached at the bottom of that page. After you import the project into Eclipse, it’s a good idea to use the Project – Clean menu item to rebuild the project.

This demo app was compiled with Android 4.2 (API 17). It works in all API levels from API 10 on up.


You can find examples of fragments in many places; the same goes for V4 compatibility. So, in a way, there is not a lot new here. However, if you know you want both fragments and V4 compatibility, consider using this app as a starter for your next project.



V4 compatibility library for Android

Supporting Multiple Screens


About Bill Lahti

Bill Lahti is a software engineer building mobile applications and knowledge management solutions. Two of his interests are writing for this blog and building Android apps, with strategy games being an area of particular interest.
This entry was posted in Android and tagged , , , . Bookmark the permalink.

12 Responses to Android Fragments Example

  1. Pingback: My Android Programming Tutorials By Topic | More Is Not Always Better

  2. Pingback: Android Fragment for an Item in a Store | More Is Not Always Better

  3. M Chisty says:

    This is a copied example taken from Professor Andrew T. Campbell. His original article was published here:

  4. Sluggo says:

    How would you change this code, so that instead of just changing the text in “text2” when an item is clicked, it replaces the entire DetailsFragment with for example “FragmentC” (which shows something else than a text, for instance an image)?

    • blahti says:

      To do what you want, use fragment transactions. See
      There will be changes in the layout files also. In my example, the fragment is defined in the fragment_layout.xml file. You’d leave that out and assign an id to the FrameLayout so that new fragments can be added there at the container level.
      GridFragment gf = new GridFragment ();
      final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
      ft.add (, gf, GRID_FRAGMENT_TAG);
      ft.commit ();

      Later you would add fragments at the same place.
      final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
      ft.replace (, nextGrid, GRID_FRAGMENT_TAG);
      if (nextDetail != null) ft.replace (, nextDetail, SELECTION_FRAGMENT_TAG);
      ft.setTransition (FragmentTransaction.TRANSIT_NONE);
      ft.commit ();

      (Example code here is from another app, but I hope you get the idea.)

      • Sluggo says:

        Thank you for your reply!
        I’ve been trying to create a Fragments- project for a while now, but I’m having some trouble..
        I think I understand the part you wrote here just now, but from what I understand, this text should go into TitlesFragment, which should work “as is” in landscape orientation, right?
        But in portrait- orientation, where the fragment should open in a new activity, something must be added to DetailsActivity in order to show the right Fragment?

      • blahti says:

        TitlesFragment showDetails handles the two cases: dual pane, single pane. For single pane, it starts DetailsActivity. You are correct in saying that something must be added to show the right fragment. If you look at the dual pane case in showDetails, you will see that it does about the same work as is done in DetailsActivity. So if you are writing an app where a new kind of fragment is being used, you’d have to put code in place in both places.

        By the way, there is a good reference out there on use of fragments. See

  5. Mike Manuka says:

    Example code is great, but just too elaborate for me. I encountered fragments before listviews, listfragments and the like. Would do anything for a simple example with 2 buttons in the navigation pane and a textview in the details pane.

  6. Ger says:

    Thanks for putting up the source code for this example.

    I’ve one question:
    – When in Landscape mode if you press e.g. ‘Henry V’, the details are displayed in the fragment on the right hand side.

    – Then if you press e.g. ‘Henry VIII’, the details for this are displayed on the right hand side, replacing the previous details.

    – If you press the Back button, the application finishes.

    – My question is – when you press the back button should you not be brought back from ‘Henry VIII’ to ‘Henry V’ instead of exiting the application?
    Implementing this will cause extra work if you revert to portrait as the extra fragments will have to be ignored?

    Just wondering if I’m right in what I’m saying or is this the official Android way of dealing with the back button in Landscape mode for fragments?

  7. GimmeShelter says:

    Very nice example for Android fragments. Thanks!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.