Android零基础入门第27节:正确使用padding和margin

本文是Android零基础入门系列的第27节,主要讲解LinearLayout线性布局中的内边距padding和外边距margin。通过示例详细解析了如何设置组件的padding和margin,并解释了它们的区别和作用,帮助初学者正确使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前面两期我们学习了LinearLayout线性布局的方向、填充模型、权重和对齐,那么本期我们来学习LinearLayout线性布局的内边距和外边距。

关于padding和margin,很多同学傻傻分不清,相信通过今天的学习可以正确使用。

一、内边距padding

默认情况下,组件相互之间是紧紧靠在一起的。但是有时候需要组件各边之间有一定的内边距,那就可以通过以下几个属性来设置,内边距的值是具体的尺寸,如5dp。

  • android:padding:为组件的四边设置相同的内边距。

  • android:paddingLeft:为组件的左边设置内边距。

  • android:paddingRight:为组件的右边设置内边距。

  • android:paddingTop:为组件的上边设置内边距。

  • android:paddingBottom:为组件的下边设置内边距。

内边距的原理如下图所示:

接下来通过一个简单的示例程序来学习android:padding的使用用法。

继续使用app/main/res/layout/目录下的activity_main.xml文件,在其中填充如下代码片段:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="padding"
        android:padding="20dp"
        android:background="#00ffff"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="normal"
        android:background="#caa926"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="padding"
        android:paddingLeft="50dp"
        android:paddingRight="50dp"
        android:paddingTop="50dp"
        android:paddingBottom="50dp"
        android:background="#00f05f"/>
</LinearLayout>

运行程序,可以看到下图所示界面效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值