Adding positive / negative Button to DialogFragment's Dialog

前端 未结 5 513
迷失自我
迷失自我 2020-12-08 13:15

I\'ve already written a DialogFragment. Now I\'ve realized that I want it to have a positive and a negative button just like an AlertDialog. How can I achieve such a thing w

5条回答
  •  隐瞒了意图╮
    2020-12-08 14:10

    To add action buttons call the setPositiveButton() and setNegativeButton() methods:

    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();
    }
    }
    

    More information about DialogFragment here.

提交回复
热议问题