前面两期我们学习了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>
运行程序,可以看到下图所示界面效果: