问题描述
这就是问题:我想以编程方式添加一些图像.除第一个图像外,图像还必须具有topMargin
的5dip
,并以vertical orientation
的方式使用LinearLayout
.在代码段下方:
Here's the thing: I want to add some images programmatically. The images should have to have a topMargin
of 5dip
except for the first image, in a LinearLayout
with a vertical orientation
manner. below the code segment:
LinearLayout body = (LinearLayout) findViewById(R.id.body);
for (int i = 1; i <= 4; i++) {
ImageView img = new ImageView(this);
MarginLayoutParams lp = new MarginLayoutParams(-2, -2);
img.setImageResource(R.drawable.image);
if (i != 1) {
lp.setMargins(0, 5, 0, 0);
}
img.setLayoutParams(lp);
body.addView(img);
body.requestLayout();
}
通过运行程序,我可以看到4个图像(此处)一一垂直对齐,但是没有topMargin
(如代码中的5dip
). body
是LinearLayout
的id
.这是XML
段:
By running the program I can see the the 4 images(here) vertically aligned one by one but there is no topMargin
(as in the code,5dip
). body
is the id
of the LinearLayout
. here's the XML
segment to:
<LinearLayout
android:id="@+id/body"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#901b0e08"
android:orientation="vertical"
android:paddingLeft="6dp"
android:paddingRight="8dp" >
</LinearLayout>
我无法理解这里出了什么问题.
I cant get what went wrong here.
谢谢.
推荐答案
尝试将您的MarginLayoutParams
更改为此:
LayoutParams lp = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT );
之所以这样做,是因为body
是LinearLayout
,因此您可能想使用特定于LinearLayout
的LayoutParams
.
The reason for doing this, is that body
is a LinearLayout
and thus you would want to use the LinearLayout
-specific LayoutParams
.
这篇关于MarginLayoutParams.setMargins()无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!