Recent Changes‎ > ‎

Fragment Support

posted May 26, 2011, 9:08 AM by Tor Norbye   [ updated May 26, 2011, 9:40 AM ]
ADT now support fragments. Let's open the 2011 IO Scheduling Application (source code) and open the activity_home layout (and open the tablet size configuration):

As you can see, the tablet landscape layout has 3 fragments. At runtime, the Fragment classes will determine which layout to use to render the layout. However, just like we let you configure ListView layouts for designtime, you can now designate layouts to use in the tool:
You can either select "Choose Layout..." to pick an arbitrary layout, or choose the suggestion (which is based on skimming the associated Fragment class). Choosing the dashboard layout gives us this:
And yes, this association between a fragment and its preview-layout is persisted across IDE sessions.

Let's configure the other two fragments as well. The bottom fragment is used to show different layouts depending on whether the scheduling app is run before, during or after the conference so there are several suggested layouts:
Here's how the layout editor looks once we've configured all the layouts:
The outline displays the fragment class names now rather than <fragment>, and you can drag in new fragments from the palette. When you do, you get a fragment chooser dialog letting you pick the Fragment class to be associated with the <fragment> tag:
Finally, if you are targeting a project earlier than Honeycomb, you'll need to use the fragments compatibility library which is a backport of the fragments support that was added for Honeycomb. The fragment features above work with both "builtin" fragments and compatibility library fragments.

When you drag a <fragment> tag into a project that isn't targetting Honeycomb or higher, you will get an error message explaining that you need to add the compatibility library. You can right click on the project, choose Android Tools > Add Compatibility Library:
This will automatically run the SDK manager, install the compatibility library, then copy the relevant jar into your libs/ folder and finally add it to your project's build path.

In more recent builds (which did not make it by the ADT 11 cutoff date) this is even more automated, such that when you drop the <fragment> tag, the warning dialog has a button to let you directly install the library and then it proceeds to the class chooser dialog. (The "Create New..." button to create a new fragment class from within the class chooser, shown above, was also added after the ADT 11 cutoff.)
Comments