这一次我们来讨论一下LinearLayout这种布局方式。相对来说,这个布局方式还比较简单。通过设置它的属性android:orientation来决定其包含的View是以水平方向还是垂直方向摆放。
Constant
Value
Description
horizontal
0
Defines an horizontal widget.
vertical
1
Defines a vertical widget.
即android:orientation="horizontal"或者android:orientation="vertical"。
如果我们选择的是水平摆放(horizontal),那么LinearLayout所包含的View会一个挨着一个在一行摆放,所有的View都在一行中,就像下图这样:
如果我们选择的是水平摆放(vertical),那么LinearLayout所包含的View会一个挨着一个竖着摆放,每个View占一行,就像下图这样:
从上面两个效果图,可以很清晰看出两种不同的布局方式差异很大。我们一共使用的是一个TextView和四个按钮。正常情况下它们应该都显示出来,但是我 们看到水平摆放时,第三个按钮已经挤成一团了,第四个按钮甚至没有显示了。而垂直摆放时,这五个view都显示出来了,每个View各自单独占一行。
padding
接下来,我们再为LinearLayout增加一种新的属性:padding。我对它的解释是边缘补白(留空白),就是让 LinearLayout中的内容距离边缘留出一定的空白,这其实是为了美观,好看。现在让我们来看看实际效果,就以上面的五个View为例吧,给 LinearLayout增加下面两个属性值:
android:paddingLeft="16dp"
android:paddingRight="16dp"
运行效果如下图所示:
可以很明显的看出来,在这些View的左边出现了一些空白,是不是?
下面,我们来看官网上的一个例子:
<?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:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical" >
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/to" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/subject" />
<EditText
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="@string/message" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="@string/send" />
</LinearLayout>
我们先看看它的运行效果是什么样子的:
这个界面有点类似于电子邮件的书写界面。 我们细看一下那个XML布局文件的内容。
<LinearLayout>元素的几个属性我们在前面的介绍中,基本上已经扫清了。除了那个fill_parent,暂时我还没有分清它与match_parent的区别,不过这个并不影响我们看其它的View。
在<LinearLayout>中有三个<EditText>和一个<Button>。三 个<EditText>中都有两个我们已经熟悉的属性,那就是androdi:layout_width和 android:layout_height。而它们的取值出现了一些新的变化。
首先,fill_parent,我们可以理解为LinearLayout允许有多宽,我就扩展为多宽。