2011-01-25 48 views
0

這是我的問題。我想要一個AlertDialog,它有一個標題和一個肯定的按鈕。我想在XML文件中描述AlertDialog的內容(標題/按鈕除外)。 我在佈局資源中創建了一個名爲dlg_addpwd.xml的文件。 這裏是代碼我使用:如何定義AlertDialog的視圖XML文件中描述的視圖

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

我猜線

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

是錯誤的,不是嗎? 所以我的問題的主要想法是:如何定義一個AlertDialog的視圖在XML文件中描述的視圖?

感謝

文森特

回答

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

這就是我該怎麼做的。

1

見我的回答Customizing the Alert dialog in Android創建一個自定義警告對話框。

您的代碼的主要問題是您不想使用AlertDialog.Builder。相反,您希望創建一個新的Dialog,並使用setContentView()來呈現您的XML。

相關問題