2011-07-12 60 views
0

我剛剛開始使用android編程,寫了一個快速代碼,並且沒有設法讓它做我想做的事。基本上,我想要一個對話框出現,2個文本框和一個特定的佈局顯示的圖像。我有以下代碼:以編程方式添加的相對佈局

AlertDialog.Builder dialog = new AlertDialog.Builder(this); 

    RelativeLayout dialogItems = new RelativeLayout(this); 
    EditText itemTitle = new EditText(this); 
    EditText itemBody = new EditText(this); 
    ImageView dIcon = new ImageView(this); 

    itemTitle.setText("Note Title"); 
    itemBody.setText("Note Details"); 
    dIcon.setImageResource(R.drawable.create); 

    final RelativeLayout.LayoutParams imageParam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
    imageParam.addRule(RelativeLayout.ALIGN_PARENT_LEFT); 
    imageParam.addRule(RelativeLayout.ALIGN_PARENT_TOP); 
    dIcon.setLayoutParams(imageParam); 
    dialogItems.addView(dIcon, imageParam); 

    final RelativeLayout.LayoutParams titleParam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
    titleParam.addRule(RelativeLayout.RIGHT_OF, dIcon.getId()); 
    titleParam.addRule(RelativeLayout.ALIGN_PARENT_TOP); 
    itemTitle.setLayoutParams(titleParam); 
    dialogItems.addView(itemTitle, titleParam); 

    final RelativeLayout.LayoutParams bodyParam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
    bodyParam.addRule(RelativeLayout.ALIGN_LEFT, itemTitle.getId()); 
    bodyParam.addRule(RelativeLayout.BELOW, itemTitle.getId()); 
    itemBody.setLayoutParams(bodyParam); 
    dialogItems.addView(itemBody, bodyParam); 

    dialog.setView(dialogItems); 

    dialog.show(); 

有沒有人知道爲什麼這不會工作?問題是,彈出窗口出現,但所有項目只是在左上角重疊。謝謝

P.S.我查了其他帖子和問題,甚至答案不工作!所以請修正我的代碼,而不是將我與另一個問題聯繫起來。

回答

4

您沒有設置ID,因此每個視圖都具有相同的ID(-1)。這應該工作:

private static final int DIALOG_ITEMS_ID = 1; 
private static final int ITEM_TITLE_ID = 2; 
private static final int ITEM_BODY_ID = 3; 
private static final int ICON_ID = 4; 

RelativeLayout dialogItems = new RelativeLayout(this); 
dialogItems.setId(DIALOG_ITEMS_ID); 
EditText itemTitle = new EditText(this); 
itemTitle.setId(ITEM_TITLE_ID); 
EditText itemBody = new EditText(this); 
itemBody.setId(ITEM_BODY_ID); 
ImageView dIcon = new ImageView(this); 
dIcon.setId(ICON_ID); 
+0

謝謝,我認爲它會給物品自己的ID自動...:P – Randomman159

相關問題