Android Programming The Big Nerd Ranch Guide, 3rd Edition

(Brent) #1

Chapter 12  Dialogs


230

Create a new class named DatePickerFragment and make its superclass DialogFragment. Be sure to
choose the support library’s version of DialogFragment: android.support.v4.app.DialogFragment.


DialogFragment includes the following method:


public Dialog onCreateDialog(Bundle savedInstanceState)


The FragmentManager of the hosting activity calls this method as part of putting the DialogFragment
onscreen.


In DatePickerFragment.java, add an implementation of onCreateDialog(Bundle) that builds an
AlertDialog with a title and one OK button. (You will add the DatePicker widget later.)


Be sure that the version of AlertDialog that you import is the AppCompat version:
android.support.v7.app.AlertDialog.


Listing 12.2  Creating a DialogFragment (DatePickerFragment.java)


public class DatePickerFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok, null)
.create();
}
}


In this implementation, you use the AlertDialog.Builder class, which provides a fluent interface for
constructing an AlertDialog instance.


First, you pass a Context into the AlertDialog.Builder constructor, which returns an instance of
AlertDialog.Builder.


Next, you call two AlertDialog.Builder methods to configure your dialog:


public AlertDialog.Builder setTitle(int titleId)
public AlertDialog.Builder setPositiveButton(int textId,
DialogInterface.OnClickListener listener)


The setPositiveButton(...) method accepts a string resource and an object that implements
DialogInterface.OnClickListener. In Listing 12.2, you pass in an Android constant for OK and
null for the listener parameter. You will implement a listener later in the chapter.


(A positive button is what the user should press to accept what the dialog presents or to take the
dialog’s primary action. There are two other buttons that you can add to an AlertDialog: a negative
button and a neutral button. These designations determine the positions of the buttons in the dialog.)


Finally, you finish building the dialog with a call to AlertDialog.Builder.create(), which returns
the configured AlertDialog instance.


There is more that you can do with AlertDialog and AlertDialog.Builder, and the details are well
covered in the developer documentation. For now, let’s move on to the mechanics of getting your
dialog onscreen.

Free download pdf