以前用wxPython做Python开发时一直没有搞清楚margin和padding的区别和用法,也没有去深究。但是这两个属性在图形布局时非常重要,下面结合例子说一下这两个属性的区别与用法。
下文中只设置了layout_margin和padding属性,View属性中还可以分别设置其right|left|top|bottom四个方向的值,如果只设置layout_margin或padding一个属性,那么表示将其四个 方向的值都指定为layout_margin或padding指定的值。
首先,我们可以打开手机开发者选项中的“显示布局边界”选项,这样方便我们观察到各个布局的详细信息。
然后新建一个工程,添加一个TextView控件,并设置如下属性。
<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"
tools:context="${relativePackage}.${activityClass}" >
<!-- 设置TextView的背景色,方便观察,设置控件的宽高,设置文本的对齐方式 -->
<TextView
android:id="@+id/textView"
android:text="TextView"
android:layout_centerInParent="true"
android:background="#FFF5EE"
android:gravity="left|top"
android:layout_width="200dp"
android:layout_height="100dp" />
</RelativeLayout>
我们再添加一个layout_margin属性:
<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"
tools:context="${relativePackage}.${activityClass}" >
<!-- 设置TextView的背景色,方便观察,设置控件的宽高,设置文本的对齐方式 -->
<TextView
android:id="@+id/textView"
android:text="TextView"
android:layout_centerInParent="true"
android:background="#FFF5EE"
android:gravity="left|top"
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_margin="15dp"/> //添加了margin属性
</RelativeLayout>
我们对比图片可以看到在控件的周边有一个红色的外框(这个外框在没打开“显示布局边界”是透明的),这个就是添加layout_margin属性之后产生的效果,margin用中文表示是"边缘"的意思,主要是用来控制与其他控件之间的间隙。
我们再设置padding属性,看看控件会发生什么变化:
<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"
tools:context="${relativePackage}.${activityClass}" >
<!-- 设置TextView的背景色,方便观察,设置控件的宽高,设置文本的对齐方式 -->
<TextView
android:id="@+id/textView"
android:text="TextView"
android:layout_centerInParent="true"
android:background="#FFF5EE"
android:gravity="left|top"
android:layout_width="200dp"
android:layout_height="100dp"
android:layout_margin="15dp"
android:padding="20dp"/> //添加了padding属性
</RelativeLayout>
我们发现添加padding属性之后,控件的文本的位置与边框之间的距离改变了,而改变的值就是padding所指定的值,所以padding是控制控件内容与边框之间的空隙。这里的控件内容就是"TextView"文本。我们设置了padding属性为20dp,那么"TextView"离四个边框的距离都应该是"20dp",但是由于文本离右边框和下边框远大于20dp,而我们的控件大小又是确定的,所以右边和下边的padding相当于无效。我们一般不会将padding_left|right|top|bottom四个属性都设置,而是根据文本的对方方式,只需要设置其中的两个或一个属性即可。
padding的中文解释是“填料,填充 ”的意思,也就是相当于在"TextView"周围填充“空白”,对于上个例子,我们可以想像成在“TextView”的右边和下边已经填充了“空白”,只是在布局中没有明显地表现出来,我们看不见而已。
由上可知:
margin属性是控制控件与控件之间的间隙,属于对控件外部的控制。
padding属性是控制控件内容与边框之间的间隙,属于对控件内部的控制。