In the Android docs on AlertDialog, it gives the following instruction and example for setting a custom view in an AlertDialog:
If you want to display a more complex view, look up the FrameLayout called "body" and add your view to it:
FrameLayout fl = (FrameLayout) findViewById(R.id.body);
fl.add(myView, new LayoutParams(FILL_PARENT, WRAP_CONTENT));
First off, it's pretty obvious that add()
is a typo and is meant to be addView()
.
I'm confused by the first line using R.id.body. It seems that it's the body element of the AlertDialog ... but I can't just enter that in my code b/c it gives a compile error. Where does R.id.body get defined or assigned or whatever?
Here's my code. I tried to use setView(findViewById(R.layout.whatever)
on the builder but it didn't work. I'm assuming because I didn't manually inflate it?
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title")
.setCancelable(false)
.setPositiveButton("Go", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
EditText textBox = (EditText) findViewById(R.id.textbox);
doStuff();
}
});
FrameLayout f1 = (FrameLayout)findViewById(R.id.body /*CURRENTLY an ERROR*/);
f1.addView(findViewById(R.layout.dialog_view));
AlertDialog alert = builder.create();
alert.show();
AlertDialog.setView(View view) does add the given view to the R.id.custom FrameLayout. The following is a snippet of Android source code from AlertController.setupView() which finally handles this (mView is the view given to AlertDialog.setView method).
It would make the most sense to do it this way, least amount of code.
For an expanded list of things you can set, start typing
.set
in Android StudioThis worked for me:
The easiest way to do this is by using
android.support.v7.app.AlertDialog
instead ofandroid.app.AlertDialog
wherepublic AlertDialog.Builder setView (int layoutResId)
can be used below API 21.The android documents have been edited to correct the errors.
The view inside the AlertDialog is called
android.R.id.custom
http://developer.android.com/reference/android/app/AlertDialog.html
The simplest lines of code that works for me are are follows:
Whatever the type of layout(LinearLayout, FrameLayout, RelativeLayout) will work by
setView
and will just differ in the appearance and behavior.