Android Programming The Big Nerd Ranch Guide, 3rd Edition

(Brent) #1

Chapter 7  UI Fragments and the Fragment Manager


148

Adding a UI Fragment to the FragmentManager


When the Fragment class was introduced in Honeycomb, the Activity class was changed to include a
piece called the FragmentManager. The FragmentManager is responsible for managing your fragments
and adding their views to the activity’s view hierarchy (Figure 7.18).


The FragmentManager handles two things: a list of fragments and a back stack of fragment transactions
(which you will learn about shortly).


Figure 7.18  The FragmentManager


For CriminalIntent, you will only be concerned with the FragmentManager’s list of fragments.


To add a fragment to an activity in code, you make explicit calls to the activity’s FragmentManager.
The first step is to get the FragmentManager itself. Do so in onCreate(Bundle) in
CrimeActivity.java.


Listing 7.15  Getting the FragmentManager (CrimeActivity.java)


public class CrimeActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);


FragmentManager fm = getSupportFragmentManager();
}
}


If you see an error after adding this line of code, check the import statements to make sure that the
support version of the FragmentManager class was imported.


You call getSupportFragmentManager() because you are using the support library and the
AppCompatActivity class. If you were not interested in using the support library, then you would
subclass Activity and call getFragmentManager().

Free download pdf