尝试使用ViewGroup.MarginLayoutParams为您的ImageView
设置边距。这里是@Hiren Patel答案中的一个方法,对我来说非常完美。
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();
}
}
如何在您的代码中使用的示例:
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);
}
我的测试布局:
<?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>
希望这能有所帮助!