Android setMargins not working programmatically

Viewed 4526
<RelativeLayout>

    ...

    <ImageView
      android:id="@+id/imageView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_marginLeft="10dp"
      android:layout_marginTop=”11dp”
      android:background=”@drawable/image”  />

</RelativeLayout>

Then I need to set the Margin programmatically:

ImageView imageView = (ImageView) findViewRoot(R.id.imageView1);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
params.width = 100;
params.height = 100;
params.setMargins(0,0,0,0); //NOT WORK
imageView.setLayoutParams(params);

The ImageView still has marginLeft 10 and marginTop 11;

What is wrong?

4 Answers

Hope this help put your ImageView in RelativeLayout and set it's width and height to Match-Parent

 <RelativeLayout
                android:id="@+id/lay_expandable"
                android:layout_width="match_parent"
                android:layout_height="200dp"
                >

                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:src="@mipmap/ic_expansion" />

            </RelativeLayout>

and in your activity use LinearLayout.LayoutParams for example

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
                    (LinearLayout.LayoutParams.MATCH_PARENT, 400);
            lay_layout.setLayoutParams(params);

// note expand the relative layout, not the image itself

This can be useful for someone: In my case I was dealing with the same problem, that margins was not being recognized on android api 19, so what I did, it was to change the size of the image (increase a bit), and then adjust padding, like follows:

file: dimens.xml
<dimen name="image_padding_right">5dp</dimen>

then on code:

 val imageView1 = ImageView(this.activity)
 imageView1.setPadding(0,0,
 resources.getDimension(R.dimen.image_padding_right).roundToInt(), 0)
 imageView1.cropToPadding = true

the opcion cropToPadding allows you to do the workaround, in case margins dont work.

I hope it helps.

Related