【发布时间】:2023-04-09 20:52:01
【问题描述】:
我正在尝试以编程方式将一些 TextView 放入我的活动中。问题是我无法设置它们的边距(上边距),所以它们之间有一些空间。
XML 布局结构如下:
<ScrollView>
<RelativeLayout_1>
<RelativeLayout_2>
<TextView/>
<EditText/>
</RelativeLayout>
</RelativeLayout>
</ScrollView>
我省略了所有不必要的信息。
然后在我的活动中我做
mLayout = (RelativeLayout) findViewById(R.id.relative_layout);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
relativeParams.addRule(RelativeLayout.ALIGN_LEFT, R.id.handicap_layout);
relativeParams.addRule(RelativeLayout.BELOW, R.id.handicap_layout);
TextView[] texts = new TextView[6];
for(int i=0; i<6; i++) {
texts[i] = new TextView(MyActivity.this);
texts[i].setText("Text " + (i+1));
texts[i].setTextSize(20);
relativeParams.setMargins(0, 10+(10*i), 0, 0); /* trying to increase the margin */
texts[i].setLayoutParams(relativeParams);
mLayout.addView(texts[i]);
}
mLayout 指的是RelativeLayout_1,handicap_layout 指的是RelativeLayout_2。
问题是边距没有增加,TextView 显示在另一个之上。
有人有解决办法吗?谢谢!
编辑:已解决
好的,我设法解决了这个问题:LayoutParams 必须在 inside for 循环中声明。 谢谢。
【问题讨论】:
标签: android android-relativelayout margins