良好的布局设计对于UI界面至关重要,在前面也简单介绍过,目前Android中的布局主要有6种,创建的布局文件默认为RelativeLayout相对布局,而在前面的示例学习中,我们只是简单利用了一下LinearLayout线性布局,那么接下来分别对其进行详细学习。
一、认识LinearLayout
线性布局是Android中较为常用的布局方式,使用LinearLayout标签。线性布局主要有两种形式,一种是水平线性布局,一种是垂直线性布局。需要注意的是Android的线性布局不会换行,当组件一个挨着一个地排列到头之后,剩下的组件将不会被显示出来。
下表显示了LinearLayout支持的常用XML属性及相关方法的说明。
LinearLayout 包含的所有子元素都受 LinearLayout.LayoutParams 控制,因此 LinearLayout包含的子元素可以额外指定如如下属性。
-
android:layout_gravity:指定该子元素在LinearLayout中的对齐方式。
-
android:layout_weight:指定该子元素在LinearLayout中所占的权重。
二、LinearLayout详解
接下来分别从方向、填充模型、权重、对齐、内边距、外边距几个方面来进一步学习LinearLayout 的使用,当然其中一部分也适用于后续布局文件。
1、方向
通过“android:orientation”属性设置线性布局的方向,将值设置为horizontal表示行,设置为vertical表示列,默认为horizontal。
接下来通过一个简单的示例程序来学习LinearLayout 的使用用法。
同样使用WidgetSample工程,继续使用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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮一"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮二"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮三"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮四"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮五"/>
</LinearLayout>
运行程序,可以看到下图左侧所示界面效果。