在上一小节末尾的XML文件中,每个TextView标签都携带新的属性android:layout_marginTop="5dp",该属性的作用是让当前视图与上方间隔一段距离。同理,android:layout_marginLeft让当前视图与左边间隔一段距离,android:layout_marginRight让当前视图 与右边间隔一段距离,android:layout_marginBottom让当前视图与下方间隔一段距离。如果上下左右 都间隔同样的距离,还能使用android:layout_margin一次性设置四周的间距。
layout_margin不单单用于文本视图,还可用于所有视图,包括各类布局和各类控件。因为不管布局还 是控件,它们统统由视图基类View派生而来,而layout_margin正是View的一个通用属性,所以View的 子子孙孙都能使用layout_margin。在View的大家族中,视图组ViewGroup尤为特殊,它既是View的子 类,又是各类布局的基类。布局下面能容纳其他视图,而控件却不行,这正源自ViewGroup的组装特 性。View、ViewGroup、控件、布局四者的继承关系如下图所示。
除了layout_margin之外,padding也是View的一个通用属性,它用来设置视图的内部间距,并且padding也提供了paddingTop、paddingBottom、paddingLeft、paddingRight四个方向的距离属性。 同样是设置间距,layout_margin指的是当前视图与外部视图(包括上级视图和平级视图)之间的距 离,而padding指的是当前视图与内部视图(包括下级视图和内部文本)之间的距离。为了观察外部间 距和内部间距的差异,
接下来做个实验,看看layout_margin与padding究竟有什么区别。 首先创建新的活动页面,并给该页面的XML文件填入以下的布局内容:
<!-- 最外层的布局背景为蓝色 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#00aaff"
android:orientation="vertical">
<!-- 中间层的布局背景为黄色 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:background="#ffff99"
android:padding="60dp">
<!-- 最内层的视图背景为红色 -->
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0000" />
</LinearLayout>
</LinearLayout>
上面的XML文件有两层视图嵌套,第一层是蓝色背景布局里面放黄色背景布局,第二层是黄色背景布局 里面放红色背景视图。中间层的黄色背景布局,同时设置了20dp的layout_margin,以及60dp的padding,其中padding是layout_margin的三倍宽(60/20=3)。接着运行测试App,看到的演示界面 如下图所示。
从效果图可见,外面一圈间隔较窄,里面一圈间隔较宽,表示20dp的layout_margin位于外圈,而60dp的padding位于内圈。这种情况印证了:layout_margin指的是当前图层与外部图层的距离,而padding指的是当前图层与内部图层的距离。
详细如下图:
完整代码:
Java:
package com.example.chapter03;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class ViewMarginActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_margin);
}
}
res\layout\activity_view_margin.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- 最外层的布局背景设置为蓝色 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#00AAFF"
android:orientation="vertical">
<!-- 中间层的布局背景为黄色 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:background="#FFFF99"
android:padding="60dp">
<!-- 最内层的背景为红色 -->
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"/>
</LinearLayout>
</LinearLayout>
注意:运行前一定要修改清单文件(AndroidManifest.xml)
感谢观看!!!