Android Programming The Big Nerd Ranch Guide, 3rd Edition

(Brent) #1
An abstract Activity class

163

Nearly every activity you will create in this book will require the same code. To avoid typing it again
and again, you are going to stash it in an abstract class.


Right-click on the com.bignerdranch.android.criminalintent package, select New → Java Class,
and name the new class SingleFragmentActivity. Make this class a subclass of AppCompatActivity
and make it an abstract class. Your generated file should look like this:


Listing 8.7  Creating an abstract Activity (SingleFragmentActivity.java)


public abstract class SingleFragmentActivity extends AppCompatActivity {


}


Now, add the following code to SingleFragmentActivity.java. Except for the highlighted portions, it
is identical to your old CrimeActivity code.


Listing 8.8  Adding a generic superclass (SingleFragmentActivity.java)


public abstract class SingleFragmentActivity extends AppCompatActivity {


protected abstract Fragment createFragment();


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


FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);


if (fragment == null) {
fragment = createFragment();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
}
}


In this code, you set the activity’s view to be inflated from activity_fragment.xml. Then you look for
the fragment in the FragmentManager in that container, creating and adding it if it does not exist.


The only difference between the code in Listing 8.8 and the code in CrimeActivity is an
abstract method named createFragment() that you use to instantiate the fragment. Subclasses of
SingleFragmentActivity will implement this method to return an instance of the fragment that the
activity is hosting.


http://www.ebook3000.com

Free download pdf