Reputation: 3917
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.
Upvotes: 3
Views: 8445
Reputation: 7452
You probably need to set LayoutParams' gravity property, for example:
lp.gravity = 0; //AXIS_X_SHIFT
That's what works fine for me.
Upvotes: 1
Reputation: 1620
Try to set padding
but margin
for ImageView. Sometimes it works fine. Your can directly set padding size to ImageView w/o declare LayoutParams
.
Upvotes: 1
Reputation: 16570
Try changing your MarginLayoutParams
to this:
LayoutParams lp = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT );
The reason for doing this, is that body
is a LinearLayout
and thus you would want to use the LinearLayout
-specific LayoutParams
.
Upvotes: 9