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
The simplest lines of code that works for me are are follows:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(R.layout.layout_resource_id);
builder.show();
Whatever the type of layout(LinearLayout, FrameLayout, RelativeLayout) will work by setView
and will just differ in the appearance and behavior.
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).
...
FrameLayout custom = (FrameLayout) mWindow.findViewById(R.id.**custom**);
custom.addView(**mView**, new LayoutParams(FILL_PARENT, FILL_PARENT));
...
You can create your view directly from the Layout Inflater, you only need to use the name of your layout XML file and the ID of the layout in file.
Your XML file should have an ID like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dialog_layout_root"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
/>
And then you can set your layout on the builder with the following code:
LayoutInflater inflater = getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.dialog_layout, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialoglayout);
builder.show();
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 easiest way to do this is by using android.support.v7.app.AlertDialog
instead of android.app.AlertDialog
where public AlertDialog.Builder setView (int layoutResId)
can be used below API 21.
new AlertDialog.Builder(getActivity())
.setTitle(title)
.setView(R.layout.dialog_basic)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Do something
}
}
)
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Do something
}
}
)
.create();
You are correct, it's because you didn't manually inflate it. It appears that you're trying to "extract" the "body" id from your Activity's layout, and that won't work.
You probably want something like this:
LayoutInflater inflater = getLayoutInflater();
FrameLayout f1 = (FrameLayout)alert.findViewById(android.R.id.body);
f1.addView(inflater.inflate(R.layout.dialog_view, f1, false));