Custom Layout for DialogFragment OnCreateView vs. OnCreateDialog Custom Layout for DialogFragment OnCreateView vs. OnCreateDialog android android

Custom Layout for DialogFragment OnCreateView vs. OnCreateDialog


I had the same exception with the following code:

public class SelectWeekDayFragment extends DialogFragment {    @Override    public Dialog onCreateDialog(Bundle savedInstanceState) {        return new AlertDialog.Builder(getActivity())        .setMessage("Are you sure?").setPositiveButton("Ok", null)        .setNegativeButton("No way", null).create();    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.week_day_dialog, container, false);        return view;        }}

You must choose to override only one of onCreateView or onCreateDialog in a DialogFragment. Overriding both will result in the exception: "requestFeature() must be called before adding content".

Important

For complete answer check the @TravisChristian comment. As he said, you can override both indeed, but the problem comes when you try to inflate the view after having already creating the dialog view.


This first approach works for me... until I want to use FindViewByID.

I would guess that you are not scoping findViewById() to the View returned by inflate(), try this:

View view = i.inflate(Resource.Layout.frag_SelectCase, null);// Now use view.findViewById() to do what you wantb.setView(view);return b.create();


Below code comes from google guide, so the answer is that you could not do like yours in onCreateDialog(), you must use super.onCreateDialog() to get a dialog.

public class CustomDialogFragment extends DialogFragment {    /** The system calls this to get the DialogFragment's layout, regardless        of whether it's being displayed as a dialog or an embedded fragment. */    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,            Bundle savedInstanceState) {        // Inflate the layout to use as dialog or embedded fragment        return inflater.inflate(R.layout.purchase_items, container, false);    }    /** The system calls this only when creating the layout in a dialog. */    @Override    public Dialog onCreateDialog(Bundle savedInstanceState) {        // The only reason you might override this method when using onCreateView() is        // to modify any dialog characteristics. For example, the dialog includes a        // title by default, but your custom layout might not need it. So here you can        // remove the dialog title, but you must call the superclass to get the Dialog.        Dialog dialog = super.onCreateDialog(savedInstanceState);        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);        return dialog;    }}