Android Programming The Big Nerd Ranch Guide, 3rd Edition

(Brent) #1

Chapter 12  Dialogs


234

Figure 12.7  An AlertDialog with a DatePicker


Either version works fine. The newer one sure is pretty, though.


You may be wondering why you went to the trouble of defining and inflating a layout when you could
have created the DatePicker object in code, like this:


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
DatePicker datePicker = new DatePicker(getActivity());


return new AlertDialog.Builder(getActivity())
.setView(datePicker)
...
.create();
}


Using a layout makes modifications easy if you change your mind about what the dialog should
present. For instance, what if you wanted a TimePicker next to the DatePicker in this dialog? If you
are already inflating a layout, you can simply update the layout file and the new view will appear.


Also, the selected date in the DatePicker is automatically preserved across rotation. (Try it.) How does
this happen? Remember that Views can save state across configuration changes, but only if they have
an ID attribute. When you created the DatePicker in dialog_date.xml you also asked the build tools
to generate a unique ID value for that DatePicker.


If you created the DatePicker in code, you would have to programmatically set an ID on the
DatePicker for its state saving to work.

Free download pdf