Android在DialogFragment中创建自定义AlertDialog

mct*_*una 2 android android-alertdialog android-dialogfragment

我正在尝试创建一个AlertDialog,其中包含一个“下一步”和“关闭”按钮以及一个“不再显示”复选框。我为DialogFragment使用支持库。以下代码运行正常,但我想为此AlertDialog使用自己的xml布局:

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        int title = getArguments().getInt("num");

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

                builder.setTitle("ASDASDAS")
                .setPositiveButton(R.string.hello_world,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            ((MainActivity)getActivity()).doPositiveClick();
                        }
                    }
                )
                .setNegativeButton(R.string.cancel,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            ((MainActivity)getActivity()).doNegativeClick();
                        }
                    }
                );
                return builder.create();
    }
Run Code Online (Sandbox Code Playgroud)

是否可以使用我自己的xml布局创建此AlertDialog?

mct*_*una 5

这是使用您自己的xml布局在DialogFragment中创建完全自定义AlertDialog的方法。

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Get the layout inflater
    LayoutInflater inflater = getActivity().getLayoutInflater();

    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the dialog layout
    builder.setView(inflater.inflate(R.layout.dialog_signin, null))
    // Add action buttons
           .setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                   // sign in the user ...
               }
           })
           .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   LoginDialogFragment.this.getDialog().cancel();
               }
           });      
    return builder.create();
Run Code Online (Sandbox Code Playgroud)