Android Programming The Big Nerd Ranch Guide, 3rd Edition

(Brent) #1

Chapter 7  UI Fragments and the Fragment Manager


142

Creating the CrimeFragment class


Right-click the com.bignerdranch.android.criminalintent package and select New → Java Class.
Name the class CrimeFragment and click OK to generate the class.


Now, turn this class into a fragment. Update CrimeFragment to subclass the Fragment class.


Listing 7.8  Subclassing the Fragment class (CrimeFragment.java)


public class CrimeFragment extends Fragment {


}


As you subclass the Fragment class, you will notice that Android Studio finds two classes with the
Fragment name. You will see Fragment (android.app) and Fragment (android.support.v4.app).
The android.app Fragment is the version of fragments built into the Android OS. You will use the
support library version, so be sure to select the android.support.v4.app version of the Fragment class
when you see the dialog, as shown in Figure 7.15.


Figure 7.15  Choosing the support library’s Fragment class


Your code should match Listing 7.9.


Listing 7.9  Supporting the Fragment import (CrimeFragment.java)


package com.bignerdranch.android.criminalintent;


import android.support.v4.app.Fragment;


public class CrimeFragment extends Fragment {


}


If you do not see this dialog or the wrong fragment class was imported, you can manually import the
correct class. If you have an import for android.app.Fragment, remove that line of code. Import the
correct Fragment class with the Option+Return (or Alt+Enter) shortcut. Be sure to select the support
version of the Fragment class.

Free download pdf