Android控件<第十三篇>:TableLayout-表格布局

2021-09-07  本文已影响0人  NoBugException

表格布局让我想到了GridLayout(网格布局),TableLayout为表格布局,也是本章的重点所在。

TableLayout是线性布局LinearLayout的子类,属于线性布局的一个扩展,也就是说TableLayout本质上就是一个线性布局。

一般代码如下:

<TableLayout
    android:id="@+id/tableLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="0,1">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="我是表格布局的第一行"
        android:textSize="20sp"
        android:padding="20dp"
        android:layout_gravity="center"/>


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20sp"
        android:padding="20dp"
        android:text="我是表格布局的第二行"
        android:layout_gravity="center"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20sp"
        android:padding="20dp"
        android:text="我是表格布局的第三行"
        android:layout_gravity="center"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20sp"
        android:padding="20dp"
        android:text="我是表格布局的第四行"
        android:layout_gravity="center"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20sp"
        android:padding="20dp"
        android:text="我是表格布局的第五行"
        android:layout_gravity="center"/>

</TableLayout>

在TableLayout中添加几个TextView,效果如下:

图片.png

默认情况下,一个组件代表一行,也就是说,我们可以把TableLayout的行写成横向的LinearLayout,并在LinearLayout中添加几个组件,那么这样看起来表格布局中每行都几个组件了。这里我想说的是,表格布局中的TableRow可以代码一行,在TableRow下可以拥有若干组件,TableRow也是LinearLayout的子类,那么问题来了,既然TableLayoutTableRow本质上都是LinearLayout,那么为什么不使用LinearLayoutLinearLayout组合完成表格布局呢?原因是TableRowTableLayout 都有他们独特的性质。

其中TableLayout有以下几种属性可设置:

当行组件比较少时,如果都没有到达屏幕右侧,如图:

图片.png

那么,可以采用拉伸某列达到全屏的效果:

    android:stretchColumns="1,3"

添加以上配置,让第1列和第三列拉伸,以保证全屏(当其中某一行达到屏幕的由边缘,则表示该表格全屏了),如图:

图片.png

如图,第1列和第3列明显已被拉伸。

注意,stretchColumns只有在所有行都没有沾满横向屏幕时才会生效,如果有一行已经正好或者超过屏幕的宽度,那么该属性无效。

当行组件比较多时,往往会超过屏幕

图片.png

TableLayout中添加

    android:shrinkColumns="0,2"

之后,可以自动收缩第0列和第2列,shrinkColumns可以有多个取值,多个取值之间用逗号隔开。

图片.png

如图,第0列和第2列明显已被收缩。

注意:shrinkColumns只有在行超过屏幕时生效,第0列和第2列收缩的幅度是一样的。

假设原图是这样的:

图片.png

现在隐藏第0列,第1列,第4列:

    android:collapseColumns="0,1,4"

效果如下:

图片.png

如题所示,列已被隐藏。

最后,GridLayoutRecyclerView都可以达到类似的效果,如果有相应的需求,那么根据情况选择使用哪种。

[本章完...]

上一篇 下一篇

猜你喜欢

热点阅读