Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Activity: Fragment Boss


Android does not provide a way to use a resource only when a device is under a particular size, but
it does provide the next best thing. The -sw600dp configuration qualifier lets you provide resources
only when a device is above a certain size. The sw stands for “smallest width,” but refers to the screen’s
smallest dimension, and thus is independent of the device’s current orientation.


With a -sw600dp qualifier, you are saying, “Use this resource on any device whose smallest dimension
is 600dp or greater.” This is a good rule of thumb for specifying a tablet-sized screen.


What about the other part, where you want to use activity_fragment.xml on smaller
devices? Smaller devices will not match your -sw600dp resource, so the default will be used:
activity_fragment.xml.


Run CriminalIntent on a phone and on a tablet. Confirm that the single- and two-pane layouts appear
where you expect them.


Activity: Fragment Boss


Now that your layouts are behaving properly, you can turn to adding a CrimeFragment to the detail
fragment container when CrimeListActivity is sporting a two-pane layout.


You might think to simply write an alternative implementation of CrimeHolder.onClick(View)
for tablets. Instead of starting a new CrimePagerActivity, this onClick(View) would get
CrimeListActivity’s FragmentManager and commit a fragment transaction that adds a
CrimeFragment to the detail fragment container.


The code in your CrimeListFragment.CrimeHolder would look like this:


public void onClick(View view) {
// Stick a new CrimeFragment in the activity's layout
Fragment fragment = CrimeFragment.newInstance(mCrime.getId());
FragmentManager fm = getActivity().getSupportFragmentManager();
fm.beginTransaction()
.add(R.id.detail_fragment_container, fragment)
.commit();
}


This works, but it is not how stylish Android programmers do things. Fragments are intended
to be standalone, composable units. If you write a fragment that adds fragments to the activity’s
FragmentManager, then that fragment is making assumptions about how the hosting activity works, and
your fragment is no longer a standalone, composable unit.


For example, in the code above, CrimeListFragment adds a CrimeFragment to CrimeListActivity
and assumes that CrimeListActivity has a detail_fragment_container in its layout.
This is business that should be handled by CrimeListFragment’s hosting activity instead of
CrimeListFragment.


To maintain the independence of your fragments, you will delegate work back to the hosting activity by
defining callback interfaces in your fragments. The hosting activities will implement these interfaces to
perform fragment-bossing duties and layout-dependent behavior.

Free download pdf