Intro to Android

FragmentManager

When Fragment's are added to the view in an XML file, they are static and always visible to the user. You can't manage the state directly, it is tied to the state of the activity.

When you create Fragment's in code, you can dynamically manage them with the FragmentManager. You manually show, hide, and replace fragments.

Typically you declare an XML placeholder to house your fragment. A popular choice is FrameLayout with an id. If you plan to use a Fragment without a view (discussed later in this chapter), you don't need a placeholder location.

FragmentTransaction

Fragment transactions operate on Fragments. You can begin one by getting a reference to the FragmentManager and the changes will take effect when you use commit().

Adding fragment

Using add(), you supply the id of your fragment holder and a reference to the fragment you'd like created.

getSupportFragmentManager().beginTransaction()
                           .add( R.id.holder, new MyFrag() )
                           .commit();

Background fragments

Instead of using fragments to encapsulate view fragments, you can could use them to handle background processing.

To do this, you return null from onCreate() and add the fragment manually (not in XML) in the hosting activity using the FragmentManager. It's essential to use a string tag to identify the fragment since you don't have an id associated with it.

Note: You normally use this with setRetainInstance(true) to ensure that the Fragment is not destroyed on configuration changes.

Background fragments don't provide a view and are not attached a a holder in your layout. When adding a background fragment to the backstack, you must give it a "tag" so you can refer to it again. Otherwise you have no way to retrieve the fragment once the transaction is complete.

    getFragmentManager().beginTransaction()
                        .add( new MyFrag(), "tag" )
                        .commit();

Backstack

You can add fragments to the backstack. To do so, just add a call to addToBackStack(true) before the commit() in your transaction.