Creating a Dialog Fragment
You can accomplish a wide variety of dialog designs—including custom layouts and those described in theDialogs design guide—by extending
DialogFragment
and creating a AlertDialog
in the onCreateDialog()
callback method.
For example, here‘s a basic AlertDialog
that‘s managed within a DialogFragment
:
public class FireMissilesDialogFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the Builder class for convenient dialog construction AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(R.string.dialog_fire_missiles) .setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // FIRE ZE MISSILES! } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); // Create the AlertDialog object and return it return builder.create(); } }
Now, when you create an instance of this class and callshow()
on that object, the dialog appears as shown in figure 1.
Figure 1. A dialog with a message and two action buttons.
The next section describes more about using theAlertDialog.Builder
APIs to create the dialog.
Depending on how complex your dialog is, you can implement a variety of other callback methods in theDialogFragment
, including all the basic fragment lifecycle methods.
时间: 2024-08-03 23:28:01