Custom Layout for DialogFragment OnCreateView vs. OnCreateDialog

后端 未结 6 1615
庸人自扰
庸人自扰 2020-12-01 00:31

I\'m trying to create a DialogFragment using my own Layout.

I\'ve seen a couple different approaches. Sometimes the layout is set in OnCreateDialog like this: (I\'

6条回答
  •  悲哀的现实
    2020-12-01 01:15

    As @Xavier Egea says, if you have both onCreateView() and onCreateDialog() implemented, you run the risk of getting the "requestFeature() must be called before adding content" crash. This is because BOTH onCreateDialog() then onCreateView() are called when you show() that fragment as a dialog (why, I don't know). As Travis Christian mentioned, the inflate() in onCreateView() after a dialog was created in onCreateDialog() is what causes the crash.

    One way to implement both these functions, but avoid this crash: use getShowsDialog() to limit execution of your onCreateView() (so your inflate() is not called). This way only your onCreateDialog() code is executed when you are displaying your DialogFragment as a dialog, but your onCreateView() code can be called when your DialogFragment is being used as a fragment in a layout.

    // Note: if already have onCreateDialog() and you only ever use this fragment as a 
    // dialog, onCreateView() isn't necessary
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (getShowsDialog() == true) {  // **The key check**
            return super.onCreateView(inflater, container, savedInstanceState);
        } else {
            View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_alarm_dialog, null);    
            return configureDialogView(view);
        }
    }
    
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    { 
        // Return custom dialog...
        Dialog dialog = super.onCreateDialog(savedInstanceState); // "new Dialog()" will cause crash
    
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_alarm_dialog, null);    
        configureDialogView(view);
        dialog.setContentView(view);
    
        return dialog;
    }
    
    // Code that can be reused in both onCreateDialog() and onCreateView()
    private View configureDialogView(View v) {      
        TextView myText = (TextView)v.findViewById(R.id.myTextView);
        myText.setText("Some Text");
    
        // etc....
    
        return v;
    }
    

提交回复
热议问题