Android Programming The Big Nerd Ranch Guide, 3rd Edition

(Brent) #1

Passing Data Between Two Fragments


235

Your dialog is onscreen and looks good. In the next section, you will wire it up to present the Crime’s
date and allow the user to change it.


Passing Data Between Two Fragments


You have passed data between two activities, and you have passed data between two fragment-based
activities. Now you need to pass data between two fragments that are hosted by the same activity –
CrimeFragment and DatePickerFragment (Figure 12.8).


Figure 12.8  Conversation between CrimeFragment and DatePickerFragment


To get the Crime’s date to DatePickerFragment, you are going to write a newInstance(Date) method
and make the Date an argument on the fragment.


To get the new date back to the CrimeFragment so that it can update the model layer and its own
view, you will package up the date as an extra on an Intent and pass this Intent in a call to
CrimeFragment.onActivityResult(...), as shown in Figure 12.9.


Figure 12.9  Sequence of events between CrimeFragment and
DatePickerFragment


It may seem strange to call Fragment.onActivityResult(...), given that the hosting activity receives
no call to Activity.onActivityResult(...) in this interaction. However, using onActivityResult(...)
to pass data back from one fragment to another not only works, but also offers some flexibility in how
you present a dialog fragment, as you will see later in the chapter.


http://www.ebook3000.com

Free download pdf