android AlertDialog setView rules
In the provided documentation for AlertDialog
there are no restrictions on what you could set within the view of an AlertDialog.
So the custom view will take its place under the dialog's title and above the buttons which will not be affected at all.
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.
As far as I know you can add anything you wish in setView(). The positive / negative buttons will not be affected.