Try using ViewGroup.MarginLayoutParams to set margins to your ImageView
. Here is a method from @Hiren Patel answer that works perfectly for me.
private void setMargins (View view, int left, int top, int right, int bottom) {
if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
p.setMargins(left, top, right, bottom);
view.requestLayout();
}
}
Sample of how to use in your code:
public void testMargin(View view){
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
params.width = 100;
params.height = 100;
setMargins(imageView , 0, 0, 0, 0);
imageView.setLayoutParams(params);
}
My test layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_blue_light"
tools:context="com.g2o.test.TestActivity">
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:background="@android:color/holo_red_dark" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="100dp"
android:layout_marginTop="100dp"
android:adjustViewBounds="true"
android:background="@drawable/cast_ic_notification_0" />
<Button
android:id="@+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="testMargin"
android:text="Test" />" />
</RelativeLayout>
Hope this helps!!