Vincent
Vincent

Reputation: 1033

How to define as a view for an AlertDialog a view described in a XML file

Here is my problem. I would like to have an AlertDialog that have a title and a positive button. I want to describe the content of the AlertDialog in a XML file (except for the title/button). I have created a file called dlg_addpwd.xml in my layout resources. Here is the code I'm using:

  AlertDialog alert = new AlertDialog.Builder(this);  
  alert.setTitle("Password access");
  alert.setView(findViewById(R.layout.dlg_addpwd));
  alert.setPositiveButton("Add", listenAddPwdDlg);
  alert.show();

I guess the line

  alert.setView(findViewById(R.layout.dlg_addpwd));

is wrong, isn't it ? So the main idea of my question is: how to define as a view for an AlertDialog a view described in a XML file?

Thanks

Vincent

Upvotes: 0

Views: 3317

Answers (2)

FoamyGuy
FoamyGuy

Reputation: 46856

    LayoutInflater inflater = (LayoutInflater) 
        getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.paypaldialog, 
        (ViewGroup) findViewById(R.id.yourDialog));
    AlertDialog.Builder builder = new AlertDialog.Builder(YourClass.this)
        .setView(layout);
    alertDialog = builder.create();
    alertDialog.show();

that is how I do it.

Upvotes: 7

McStretch
McStretch

Reputation: 20645

See my answer to Customizing the Alert dialog in Android to create a custom Alert Dialog.

The main problem with your code is that you don't want to use AlertDialog.Builder. Instead you want to create a new Dialog, and use setContentView() to render your XML.

Upvotes: 1

Related Questions