android AlertDialog setView规则

Cyg*_*nus 14 android android-custom-view android-alertdialog

该类的setView()方法AlertDialog允许为对话框指定自定义视图.是否可以在此自定义视图中包含哪些控件?

此外,如果我们设置自定义视图,我们还可以使用添加按钮setPositiveButton(),setNegativeButton()等?

Tim*_*tje 32

AlertDialog类的setView()方法允许为对话框指定自定义视图.是否可以在此自定义视图中包含哪些控件?

AlertDialog.Builder中setView()方法接受从View扩展的任何类(参见它的子类及其子类).

这意味着EditTexts,Buttons等.还有从viewGroups扩展的Layouts.

另外,如果我们设置自定义视图,我们仍然可以使用setPositiveButton,setNegativeButton等添加按钮吗?

是的,它只影响身体.按钮添加在布局下方.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Get the layout inflater
    LayoutInflater inflater = 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.YourLayout, null))
        .setPositiveButton(AlertDialog.BUTTON_NEGATIVE, "Yes!",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    //
                }
         })
        .setNegativeButton(AlertDialog.BUTTON_NEGATIVE, "Cancel",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    LoginDialogFragment.this.getDialog().cancel();
                }
         });
    return builder.create();
}
Run Code Online (Sandbox Code Playgroud)

更新:

从2年前开始,这个答案似乎得到了一些新的活动,而且有些事情发生了变化.

我更新了代码以改进格式,并添加了以下提示,因为最佳实践的当前状态.

AlertDialog定义对话框的样式和结构,但您应该使用DialogFragment作为对话框的容器.DialogFragment类提供了创建对话框和管理其外观所需的所有控件,而不是调用Dialog对象上的方法.

上面的示例是指在扩展DialogFragment并在onCreateDialog()回调方法中创建AlertDialog时.