setView()
类的AlertDialog
方法允许为对话框指定自定义 View 。关于此自定义 View 中可以包含哪些控件,是否有任何限制?
另外,如果我们设置了自定义 View ,是否还可以使用setPositiveButton()
,setNegativeButton()
等添加按钮?
最佳答案
AlertDialog类的setView()方法允许为对话框指定自定义 View 。关于此自定义 View 中可以包含哪些控件,是否有任何限制?
AlertDialog.Builder中的setView()
方法采用从View扩展的任何类(请参见其子类及其子类)。
这意味着EditTexts,Button等。还有从viewGroups扩展的Layouts。
另外,如果我们设置了自定义 View ,是否仍可以使用setPositiveButton,setNegativeButton等添加按钮?
是的,它只影响 body 。
在布局下方添加了按钮。
@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();
}
更新:
自2年前以来,这个答案似乎有了新的发展,而且有些事情已经改变。
由于最佳实践的当前状态,我对代码进行了一些更新以改进格式并添加了以下技巧。
上面的示例意味着当您扩展
DialogFragment
并在AlertDialog
回调方法中创建onCreateDialog()
时。