MarginLayoutParams.setMargins() 不起作用?
事情是这样的:我想以编程方式添加一些图像。除第一张图像外,图像的 topMargin
必须为 5dip
,位于具有垂直方向
的 LinearLayout
中> 方式。代码段下方:
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
段:
<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>
我不明白这里出了什么问题。
谢谢。
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();
}
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.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试将您的
MarginLayoutParams
更改为:这样做的原因是
body
是LinearLayout
,因此您需要使用>LinearLayout
特定的LayoutParams
。Try changing your
MarginLayoutParams
to this:The reason for doing this, is that
body
is aLinearLayout
and thus you would want to use theLinearLayout
-specificLayoutParams
.尝试为 ImageView 设置
padding
但margin
。有时效果很好。您可以直接设置 ImageView 的填充大小,无需声明 LayoutParams 。Try to set
padding
butmargin
for ImageView. Sometimes it works fine. Your can directly set padding size to ImageView w/o declareLayoutParams
.,例如:
您可能需要设置 LayoutParams' gravity属性 对我来说效果很好。
You probably need to set LayoutParams' gravity property, for example:
That's what works fine for me.