Android margin和padding的用法和区别

923 阅读1分钟

这是我参与 8 月更文挑战的第 29 天,活动详情查看: 8月更文挑战

简介

在需求中, 经常会出现字体距边框5dp, 控件距边框10dp等等, 这个时候就会经常把margin和padding搞混, 增加开发成本,本篇就介绍margin和padding的用法和区别.

使用

四周间距

<TextView
    android:background="@color/app_theme_color"
    android:textColor="@color/black"
    android:layout_margin="15dp"
    android:textSize="16dp"
    android:text="测试控件之间边距"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

image.png

设置单边间距

<TextView
    android:background="@color/app_theme_color"
    android:textColor="@color/black"
    android:layout_marginLeft="15dp"
    android:textSize="16dp"
    android:text="测试控件之间边距"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

image.png

如果android:layout_margin和设置单边同时存在, 单边距的设置不生效

设置内容四周间距

<TextView
    android:layout_below="@id/tv_margin"
    android:background="@color/app_theme_color"
    android:textColor="@color/black"
    android:padding="15dp"
    android:textSize="16dp"
    android:text="测试内容间距"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

image.png

设置内容单边距

<TextView
    android:layout_below="@id/tv_margin"
    android:background="@color/app_theme_color"
    android:textColor="@color/black"
    android:paddingStart="15dp"
    android:textSize="16dp"
    android:text="测试内容间距"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

image.png

区别

margin是设置控件之间的边距, padding是设置内容到控件边框的间距
用一张图简单描述一下margin和padding的作用域 image.png

常用属性

android:layout_margin 统一设置四周的边距
android:layout_marginLeft 设置左边距
android:layout_marginStart 设置左边距(推荐使用)
android:layout_marginRight 设置右边距
android:layout_marginEnd 设置右边距(推荐使用)
android:layout_marginTop 设置上边距
android:layout_marginBottom 设置下边距
android:layout_padding 统一设置内容四周的距离
android:layout_paddingLeft 设置内容左边距
android:layout_paddingStart 设置内容左边距(推荐使用)
android:layout_paddingRight 设置内容右边距
android:layout_paddingEnd 设置内容右边距(推荐使用)
android:layout_paddingTop 设置内容上边距
android:layout_paddingBottom 设置内容下边距