Adding positive / negative Button to DialogFragment's Dialog

前端 未结 5 510
迷失自我
迷失自我 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 13:57

    You have to override the DialogFragments onCreateDialog(...) method:

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
    
        return new AlertDialog.Builder(getActivity())
                .setTitle("title")
                .setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            // do something...
                        }
                    }
                )
                .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.dismiss();
                        }
                    }
                )
                .create();
    }
    

    Taken from here: Android: disable DialogFragment OK/Cancel buttons

    According to the error message you are getting ("request feature must be called...") I would recommend:

    Don't call setContentView() before requestFeature() in your Activity or wherever it is you are calling it.

    Furthermore:

    Dont call setStyle(...) inside the onCreate().

    Call it where you create your Fragment.

    YourDialogFragment f = new YourDialogFragment(Context);
    f.setStyle(...);
    // and so on ...
    

提交回复
热议问题