1. 程式人生 > >Android View設定Margin

Android View設定Margin

準備工作:  佈局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#91bef0"
    tools:context="com.example.administrator.hongyangzzq.MainActivity">

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="View Margin"
        android:textAllCaps="false"/>


    <ImageView
        android:layout_marginTop="50dp"
        android:id="@+id/iv"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@mipmap/ic_launcher"/>


</RelativeLayout>

主要內容:

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(iv.getLayoutParams());
            lp.setMargins(50,100,0,0);
            iv.setLayoutParams(lp);
為了一勞永逸 寫成工具類:
public class MarginUtils {

    public static void setMargin(View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }

}