相对布局无法以编程方式添加

时间:2011-07-12 14:45:55

标签: android android-layout

我刚开始使用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。我已经检查了其他帖子和问题,甚至答案都不起作用!所以请修改我的代码而不是将我链接到另一个问题。

1 个答案:

答案 0 :(得分: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);