元素在动态生成的android布局中重叠

时间:2014-10-22 13:46:00

标签: java android android-relativelayout

我正在以编程方式为相对布局生成元素,每次都要满足不同数量的元素。我可以使TextView和EditText元素正确显示,彼此之下没有重叠,但第二个我添加了复选框和按钮一切都变得一团糟。这是我的代码:

RelativeLayout mRlayout = (RelativeLayout) findViewById(R.id.checkFieldsLayout);

for (int i = 1; i < fields.size(); i++) {
    RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(
             RelativeLayout.LayoutParams.MATCH_PARENT,
             RelativeLayout.LayoutParams.WRAP_CONTENT);
        params1.addRule(RelativeLayout.BELOW,fields.size()+i -1);

    RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    params2.addRule(RelativeLayout.BELOW, i);

    String thisHeader = fields.get(i).replace("_", " ").toString();

    if (thisHeader.contains("chkbox")) {
        CheckBox chkbox = new CheckBox(this);
        chkbox.setId(i);
        chkbox.setText(thisHeader);
        chkbox.setLayoutParams(params1);
        mRlayout.addView(chkbox);

        if (thisHeader.contains("chkboximg")) {
            Button upload_btn = new Button(this);
            upload_btn.setId(i);
            upload_btn.setLayoutParams(params1);
            upload_btn.setText("Select Image");
            upload_btn.setOnClickListener(this);
            mRlayout.addView(upload_btn);
        }

    } else {
        TextView header = new TextView(this);
        header.setText(StringUtils.capitalize(thisHeader));
        header.setId(i);
        header.setLayoutParams(params1);

        EditText field = new EditText(this);
        field.setLayoutParams(params2);
        field.setId(fields.size() + i);

        mRlayout.addView(header);
        mRlayout.addView(field);
    }
}

有人能弄清楚如何正确设置布局参数,以便每个元素都显示在前一个元素下面吗?

1 个答案:

答案 0 :(得分:0)

您可能最好定义您在XML中添加的视图并在此处充气,而不是在代码中使用布局参数。您可以通过将可见性设置为Visible或Gone来打开和关闭部件。