1

我想动态创建4个RelativeLayout,以便每个后续布局都放在前一个布局之下。我正在尝试使用这段代码来做到这一点:

RelativeLayout layoutParent = (RelativeLayout)findViewById(R.id.layoutParent);
    int layouts = 4;

        int dp15 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics());

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
            params.setMargins(dp15, dp15, dp15, dp15);


        for (int l = 0; l <= layouts; l++)
        {
            RelativeLayout queueLayout = new RelativeLayout(getApplicationContext());
            TextView one = new TextView(getApplicationContext());
            one.setText(String.valueOf(l));
            queueLayout.setId(2000 + l);
            if (l != 0) params.addRule(RelativeLayout.BELOW, queueLayout.getId() - 1);
            queueLayout.addView(one, params);
            layoutParent.addView(queueLayout);
        }

但我无法获得每个布局的所需位置。有人能告诉我怎么做我想做的事吗?

先感谢您!

4

1 回答 1

2

您设置了BELLOW规则,但在将子项添加到父布局时从不使用它RelativeLayout(如 MisterSquonk 所说)。LayoutParams还为孩子使用另一组RelativeLayout

for (int l = 0; l <= layouts; l++) {
        RelativeLayout queueLayout = new RelativeLayout(getApplicationContext());
        TextView one = new TextView(getApplicationContext());
        one.setText(String.valueOf(l));
        queueLayout.setId(2000 + l);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        if (l != 0) lp.addRule(RelativeLayout.BELOW, queueLayout.getId() - 1);
        queueLayout.addView(one, params);
        layoutParent.addView(queueLayout, lp);
    }
于 2012-04-08T18:43:03.553 回答