Adding positive / negative Button to DialogFragment's Dialog

前端 未结 5 519
迷失自我
迷失自我 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:02

    The clearest way.

    // Your own onCreate_Dialog_View method
    public View onCreateDialogView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.your_layout, container); // inflate here
    }
    
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    
        // do something with 'view'
    }
    
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // setup dialog: buttons, title etc
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity())
                .setTitle(R.string.dialog_fragment_author_title)
                .setNegativeButton(R.string.dialog_fragment_author_close,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                dialog.dismiss();
                            }
                        }
                );
    
        // call default fragment methods and set view for dialog
        View view = onCreateDialogView(getActivity().getLayoutInflater(), null, null);
        onViewCreated(view, null);
        dialogBuilder.setView(view);
    
        return dialogBuilder.create();
    }
    

提交回复
热议问题