1. 程式人生 > >Andorid 佈局layout_margin和padding分析

Andorid 佈局layout_margin和padding分析

很長時間對於margin和padding的作用區別模糊,不知道有什麼區別。

這次經過試驗終於搞清楚了:

margin是控制元件或者佈局的整體區域,相對於父佈局以及周圍控制元件和佈局的上下左右的距離。

padding是當前控制元件或者佈局的有效區域(比如下圖中紅色的文字輸入框的輸入區域),相對於控制元件或者佈局的整體區域的邊界的上下左右的距離。


佈局檔案如下:

看這個標識圖則一目瞭然


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="姓名"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="5"
            android:hint="請輸入您的姓名" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" 
        android:layout_marginTop="100dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginBottom="100dp"
        
        >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="5"
            android:text="年齡"
            android:textSize="18sp" />
        <View
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="@color/dividingline_color" />

        <EditText
            android:id="@+id/age"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingTop="30dp"
            android:paddingBottom="30dp"
            android:paddingLeft="30dp"
            android:paddingRight="30dp"
            
            android:background="#aa0000"
            android:hint="請輸入您的年齡" />
    </LinearLayout>

</LinearLayout>