【Android】36、基本布局——TableLayout

来源:互联网 发布:ubuntu软件更新器 编辑:程序博客网 时间:2024/06/07 02:25

本篇博文最后修改时间:2016年7月20日,23:34


一、简介

本篇介绍基本布局——TableLayout


二、实验平台
系统版本:Windows7 家庭普通版 32位操作系统。

三、版权声明
博主:思跡
声明:喝水不忘挖井人,转载请注明出处。
原文地址:http://blog.csdn.net/omoiato

联系方式:315878825@qq.com

Java零基础入门交流群:541462902


四、基本布局——TableLayout

TableLayout 允许我们使用表格的方式来排列控件,

这种布局也不是很常用,我们只需要了解一下它的基本用法就可以了。

既然是表格,那就一定会有行和列,

在设计表格时我们尽量应该让每一行都拥有相同的列数,

这样的表格也是最简单的。不过有时候事情并非总会顺从我们的心意,

当表格的某行一定要有不相等的列数时,就需要通过合并单元格的方式来应对。

比如我们正在设计一个登录界面, 允许用户输入账号密码后登录, 

就可以将activity_main.xml 中的代码改成如下所示:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"        android:layout_height="match_parent" >    <TableRow>            <TextView            android:layout_height="wrap_content"            android:text="Account:" />        <EditText            android:id="@+id/account"            android:layout_height="wrap_content"            android:hint="Input your account" />    </TableRow>    <TableRow>        <TextView            android:layout_height="wrap_content"            android:text="Password:" />        <EditText            android:id="@+id/password"            android:layout_height="wrap_content"            android:inputType="textPassword" />    </TableRow>     <TableRow>        <Button            android:id="@+id/login"            android:layout_height="wrap_content"            android:layout_span="2"            android:text="Login" />    </TableRow></TableLayout>


在TableLayout 中每加入一个TableRow 就表示在表格中添加了一行,

然后在TableRow中每加入一个控件,就表示在该行中加入了一列,

TableRow 中的控件是不能指定宽度的。
这里我们将表格设计成了三行两列的格式

第一行有一个TextView 和一个用于输入账号的EditText ,

 第二行也有一个TextView 和一个用于输入密码的EditText ,

 我们通过将android:inputType 属性的值指定为textPassword,把EditText 变为密码输入框。

可是第三行只有一个用于登录的按钮,前两行都有两列,第三行只有一列,

这样的表格就会很难看,而且结构也非常不合理。

这时就需要通过对单元格进行合并来解决这个问题,

 使用android:layout_span="2"让登录按钮占据两列的空间,就可以保证表格结构的合理性了。


不过当前的登录界面并没有充分利用屏幕的宽度,右侧还空出了一块区域,

因为在TableRow 中我们无法指定控件的宽度。

这时使用android:stretchColumns 属性就可以很好地解决这个问题,

它允许将TableLayout 中的某一列进行拉伸,以达到自动适应屏幕宽度的作用。

修改activity_main.xml 中的代码:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"        android:layout_height="match_parent"    android:stretchColumns="1"    >    ……</TableLayout>


这里将android:stretchColumns 的值指定为1,

表示如果表格不能完全占满屏幕宽度,将第二列进行拉伸。

指定成1 就是拉伸第二列,指定成0 就是拉伸第一列

0 0
原创粉丝点击