margin和padding 的区别

经常会看到这样的布局android:Layout_marginTop="-1.0dip",比较迷惑。查了下资料,有篇文章讲的不错,拿来一起分享!

就拿Layout_marginTop和PaddingTop为例。
       Layout_marginTop是从当前设定的控件的头部,开始向上移动,直到碰到上一个控件/父容器的顶部,所经过的距离。为什么这边要用“或”呢,因为在不同的Layout的效果是不一样的。在LinearLayout中,已经为内容控件规定了是按顺序排列的,所以Layout_marginTop的距离是指离上一个控件的底部的距离(垂直线性布局),但是在 RelativeLayout中,控件可以选择性堆叠在一起,所以,在RelativeLayout中的控件之间没有位置上的关系的话,那当前控件的 Layout_marginTop就是指到父容器顶部的距离。

   PaddingTop是指从父容器的顶部触发,向下移动,碰到的第一个控件的顶部的距离。这个还是很好理解的。

当父容器设置了paddingTop,子元素又设置了Layout_marginTop了的话,那两者的距离就是两个值的相加了。

Layout_marginTop那一段可能说的有点绕,发点代码上来,大家试试就能理解了。

<?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="horizontal" >

     <RelativeLayout

             android:layout_width="fill_parent"

             android:layout_height="fill_parent"

             android:layout_weight="1"

             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:layout_marginTop="20dp"

             android:orientation="vertical">

             <Button

                     android:layout_width="wrap_content"

                     android:layout_height="wrap_content"

                     android:text="button3"/>

             <Button

                     android:layout_width="wrap_content"

                     android:layout_height="wrap_content"

                     android:text="button4"

                     android:layout_marginTop="20dp"/>

     </LinearLayout>

</LinearLayout>
示例图:
margin和padding <wbr>的区别
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值