<RelativeLayout>\n\n ...\n\n <ImageView\n android:id="@+id/imageView1"\n android:layout_width="wrap_content"\n android:layout_height="wrap_content"\n android:layout_alignParentLeft="true"\n android:layout_marginLeft="10dp"\n android:layout_marginTop=\xe2\x80\x9d11dp\xe2\x80\x9d\n android:background=\xe2\x80\x9d@drawable/image\xe2\x80\x9d />\n\n</RelativeLayout>\nRun Code Online (Sandbox Code Playgroud)\n\n然后我需要以编程方式设置边距:
\n\nImageView imageView = (ImageView) findViewRoot(R.id.imageView1);\nRelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();\nparams.width = 100;\nparams.height = 100;\nparams.setMargins(0,0,0,0); //NOT WORK\nimageView.setLayoutParams(params);\nRun Code Online (Sandbox Code Playgroud)\n\nImageView仍然有marginLeft 10和marginTop 11;
\n\n怎么了?
\n尝试使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
如何在代码中使用的示例:
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);
}
Run Code Online (Sandbox Code Playgroud)
我的测试布局:
<?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>
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!!
| 归档时间: |
|
| 查看次数: |
5932 次 |
| 最近记录: |