网上有人比喻的很好:布局好比是建筑里的框架,组件按照布局的要求依次排列,就组成了用于看见的漂亮界面了。
一、布局类型
1. LinearLayout (线性布局)
LinearLayout 是最常用的布局方式,在 XML 文件中使用 标记。它会将容器里的 UI 组件一个一个挨着排列起来。但是 LinearLayout 不会换行,当 UI 组件超出屏幕之后,则不会被显示出来。 LinearLayout 有两个重要的 XML 属性:android:gravity(对齐方式);android:orientation(排列方式)。
android:orientation(排列方式),设定了 LinearLayout 中包含的 UI 组件的排列方式,有两个选项vertical(竖向)、horizontal(横向,默认值)
android:gravity(对齐方式),设定 LinearLayout 中包含 UI 组件的对齐方式,其选项很多,常用上(top)、下(bottom)、左(left)、右(right)。
- 示例代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="4" >
</Button>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="5" >
</Button>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="6" >
</Button>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="+" >
</Button>
</LinearLayout>
2. RelativeLayout (相对布局)
RelativeLayout,其内子组件的位置总是相对兄弟UI组件、父亲容器来决定的。比如UI组件A相对于UI组件B的位置进行定位,那么UI组件B需要在UI组件A之前定义。
相对布局用到的主要属性:
- android:layout_below:在某元素的下方。
- android:layout_above:在某元素的上方。
- android:layout_toLeftOf:在某元素的左边。
- android:layout_toRightOf:在某元素的右边。
- android:layout_alignXxx:控制与某元素的边界对其方式。
- 示例代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:text="Button1"
></Button>
<Button android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/btn1"
android:layout_above="@id/btn1"
android:text="Button2"
></Button>
<Button android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/btn1"
android:layout_above="@id/btn1"
android:text="Button3"
></Button>
<Button android:id="@+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/btn2"
android:layout_toLeftOf="@id/btn3"
android:layout_above="@id/btn2"
android:text="Button4"
></Button>
</RelativeLayout>
3. TableLayout (表格布局)
表格布局,采用行、列的形式来管理UI组件,TableLayout 通过 TableRow、其他UI组件来控制表格的行数和列数。
每次向 TableLayout 中添加一个 TableRow,该 TableRow 就是一个表格行,TableRow 也是容器,因此它也可以不断添加其他组件,没添加一个子组件,该表格就增加一列。如果直接向 TableLayout