1. 程式人生 > >Android開發中佈局與元件(二)—— padding 與 margin 的區別

Android開發中佈局與元件(二)—— padding 與 margin 的區別

在 Android開發中我們會設定某個檢視相對於別的檢視的距離,這時我們就要用到 marginpadding ,但是有時候很容易把這兩個屬性弄混淆,那我們就看看他們的區別。

  • 外邊距(margin): 屬於佈局引數,決定兩個元件之間的距離。作用於多個元件之間。
  • 內邊距(padding):不屬於佈局引數,這個引數是為了告訴元件在繪製自己的時候應該比自己的內容(content)大多少。作用於元件自己。

具體情況如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android
="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffca">
<TextView android:id="@+id/text1" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_margin="8dp" android:text="text1" android:textSize="30sp" android:background="#ff0000"/>
<TextView android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below
="@id/text1" android:layout_margin="8dp" android:padding="8dp" android:text="text2" android:textSize="30sp" android:background="#0000ff"/>
</RelativeLayout>

效果圖如下:

在我們程式碼中定義的兩個 TextView 中唯一的區別是 text2text1 多了一個 android:padding="8dp" 屬性,從而使他們的表現出來的樣子大不相同,在 text2text1 中同時定義的 android:layout_margin="8dp" 屬性是讓父檢視在佈置他們的位置是注意保持他們周圍的邊距為 8dp ,即 text1 距螢幕頂部的距離是 8dp ,距螢幕左邊也是 8dp , text2 也是同樣的,所以就導致 text1 底部和 text2 頂部的距離就是 16dp
text2 由於有 android:padding="8dp" 的屬性,所以就導致他的實際大小要比 text1 要大,如果我們把 text1 放在 text2 上邊,就會發現 text1 的上下左右四個邊 距 text2 的四個邊的距離都是 8dp ,這就是 padding 屬性的作用,它使得元件在保證內容不變的情況下增加元件的大小。

希望可以幫到你~

PS:開發了一個製作個性二維碼的應用,有興趣的朋友可以試一試~ 創意二維碼製作