Android日记之2012\01\14
今天又发现了一个平时没有注意的地方,那就是margin和padding 的区别。
其实,两个的作用相当,都是为控件设定位置来的,但是,作用的点却不同。
就拿Layout_marginTop和PaddingTop为例。Layout_marginTop是从当前设定的控件的头部,开始向上移动,直到碰到上一个控件/父容器的顶部,所经过的距离。为什么这边要用或呢,因为在不同的Layout的效果是不一样的。在LinearLayout中,已经为内容控件规定了是按顺序排列的,所以Layout_marginTop的距离是指离上一个控件的底部的距离(垂直线性布局),但是在RelativeLayout 中,控件可以选择性堆叠在一起,所以,在RelativeLayout中的控件之间没有位置上的关系的话,那当前控件的Layout_marginTop 就是指到父容器顶部的距离。
PaddingTop是指从父容器的顶部触发, 向下移动,碰到的第一个控件的顶部的距离。这个还是很好理解的。
当父容器设置了paddingTop,子元素又设置了Layout_marginTop了的话,那两者的距离就是两个值的相加了。
Layout_marginTop那一段可能说的有点绕,发点代码上来,大家试试就能理解了。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="@drawable/bottom"
android:paddingTop="50dp"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button2"
android:layout_marginTop="20dp"/>
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="@drawable/top"
android:layout_marginTop="20dp"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button2"
android:layout_marginTop="20dp"/>
</LinearLayout>
</LinearLayout> 1 楼 oldnew 2012-01-19 简单的说 margin是向外 padding是向内