Android Programming The Big Nerd Ranch Guide, 3rd Edition

(Brent) #1

The downside to direct retrieval


209

Run CriminalIntent. Select Crime #4 and watch a CrimeFragment instance with the correct crime data
appear (Figure 10.3).


Figure 10.3  The crime that you wanted to see


The downside to direct retrieval


Having the fragment access the intent that belongs to the hosting activity makes for simple code.
However, it costs you the encapsulation of your fragment. CrimeFragment is no longer a reusable
building block because it expects that it will always be hosted by an activity whose Intent defines an
extra named com.bignerdranch.android.criminalintent.crime_id.


This may be a reasonable expectation on CrimeFragment’s part, but it means that CrimeFragment, as
currently written, cannot be used with just any activity.


A better solution is to stash the crime ID someplace that belongs to CrimeFragment rather than keeping
it in CrimeActivity’s personal space. The CrimeFragment could then retrieve this data without relying
on the presence of a particular extra in the activity’s intent. The “someplace” that belongs to a fragment
is known as its arguments bundle.


http://www.ebook3000.com

Free download pdf