The setView()
method of the AlertDialog
class allows one to specify a custom view for the dialog box. Are there any restrictions as to what controls can be included in this custom view ?
Also, if we set a custom view, can we still add buttons using setPositiveButton()
, setNegativeButton()
, etc ?
The setView() method of the AlertDialog class allows one to specify a custom view for the dialog box. Are there any restrictions as to what controls can be included in this custom view ?
The setView()
method in AlertDialog.Builder takes any class extended from View (see it's sub classes and their sub classes).
This means EditTexts, Buttons etc. But also Layouts which extend from viewGroups.
Also, if we set a custom view, can we still add buttons using setPositiveButton, setNegativeButton etc ?
Yes, it only affects the body. Buttons are added below the layout.
@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();
}
UPDATE:
This answer seem to get some new activity since 2 years ago and some things have changed.
I updated the code a little bit to improve formatting and added the following tip because of the current state of best practices.
The AlertDialog defines the style and structure for your dialog, but you should use a DialogFragment as a container for your dialog. The DialogFragment class provides all the controls you need to create your dialog and manage its appearance, instead of calling methods on the Dialog object.
The above example is meant when you extend DialogFragment
and create a AlertDialog
in the onCreateDialog()
callback method.