看了網上的相似博客,並無給出肯定的區別。如今具體分析一下padding和android:margin的區別android
首先看一張圖:
測試
顧名思義。padding爲內邊距;margin爲外邊距。code
安卓的view是一塊矩形區域,padding是內邊距,就是view(裏面的內容)永遠都至少和邊界有一段設定好的距離。margin是外邊距,就是外面的view沒法徹底靠近這個view的邊界,至少要間隔一段設置好的距離。xml
我理解成:某個View指定爲padding是針對該View裏面的子View距離該View距離而言的。某個View指定爲margin是針對該View自己距離別人或者父View而言的。blog
再看一段代碼:utf-8
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout\_width="match\_parent" android:layout\_height="match\_parent" android:orientation="vertical" android:padding="10dp" >//這裏的padding表示他的子view即下面的兩個LinearLayout與此LinearLayout的距離是10dp <LinearLayout android:id="@+id/left_layout" android:layout\_width="wrap\_content" android:layout\_height="wrap\_content" android:layout_gravity="left" android:background="@drawable/message_left" > <TextView android:id="@+id/left_msg" android:layout\_width="wrap\_content" android:layout\_height="wrap\_content" android:layout_gravity="center" android:layout_margin="10dp" android:textColor="#fff" /> </LinearLayout> <LinearLayout android:id="@+id/right_layout" android:layout\_width="wrap\_content" android:layout\_height="wrap\_content" android:layout_gravity="right" android:background="@drawable/message_right" > <TextView android:id="@+id/right_msg" android:layout\_width="wrap\_content" android:layout\_height="wrap\_content" android:layout_gravity="center" android:layout_margin="10dp" />//這表明TextView與它所在的父view即LinearLayout的距離爲10dp </LinearLayout> </LinearLayout>
經過測試,再在子LinearLayout裏面加入padding和margin的確是和所寫一致。博客
一樣地,再給出一個例子驗證所述的正確性:it
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout\_width="match\_parent" android:layout\_height="match\_parent" android:orientation="horizontal" android:padding="30dp">//表示這個view裏面的view即linerlayout與該view的邊距爲30dp <LinearLayout android:layout\_width="wrap\_content" android:layout\_height="wrap\_content" android:layout_margin="10dp" >//表示該linerlayout相對於自己與外面的view的邊距爲10dp <Button android:id="@+id/button1" android:layout\_width="wrap\_content" android:layout\_height="wrap\_content" android:layout_margin="30dp"//表示此button相對於自己與外view即linerlayout和button2(能夠直接理解成與四周的view)邊距爲30dp android:text="button1" /> <Button android:id="@+id/button2" android:layout\_width="wrap\_content" android:layout\_height="wrap\_content" android:layout_marginLeft="30dp"//表示此button相對於自己與左邊的view即button1的邊距爲30dp android:text="button2" /> </LinearLayout> </LinearLayout>
圖解以下:
io
如有其餘更好的理解,還望指正、指導。coding