O'Reilly logo

Programming Android by Zigurd Mednieks, G. Blake Meike, Masumi Nakamura, Laird Dornin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Fragment Transactions

In addition to using fragment tagging, the new code also alludes to fragment transactions. Let’s extend the application once again to demonstrate their value.

Before we take on transactions, though, we need to take a brief detour. We noted earlier that the Android Developer Documentation recommends that fragment subclasses not have explicit constructors. So, how does an external object supply initialization state for a new fragment? The Fragment class supports two methods, setArguments and getArguments, that provide this capability. Respectively, they allow an external caller—probably the fragment creator—to store a Bundle in the fragment and the fragment to recover that bundle at some later time.

This elaborate combination of a new instance of the fragment, a Bundle, and a call to setArguments functions very much like a constructor. It makes sense, then, to combine them into a static factory method in the Fragment object, like this:

public static DateTime createInstance(Date time) {
    Bundle init = new Bundle();
    init.putString(
        DateTime.TAG_DATE_TIME,
        getDateTimeString(time)); 

    DateTime frag = new DateTime();
    frag.setArguments(init);
    return frag;
}

private static String getDateTimeString(Date time) {
    return new SimpleDateFormat("d MMM yyyy HH:mm:ss")
        .format(time);
}

Now we can use the static factory method in SimpleFragment’s onCreate method to create a new instance of the fragment with its argument bundle correctly initialized. This code is nearly identical to ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required