How to implement a custom AlertDialog View


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(;
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 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 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);
    .setPositiveButton("Go", new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int id) {
        EditText textBox = (EditText) findViewById(;

FrameLayout f1 = (FrameLayout)findViewById( /*CURRENTLY an ERROR*/);

AlertDialog alert = builder.create();;
11/25/2016 2:39:10 AM

Accepted Answer

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(;
f1.addView(inflater.inflate(R.layout.dialog_view, f1, false));
5/8/2010 7:23:39 PM

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=""

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);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow