0
点赞
收藏
分享

微信扫一扫

Android开发之TableLayout

Brose 2022-03-15 阅读 60
androidui

文章目录

基本框架

先敲一个TableLayout的框架,再向其中添加一个按钮组件。

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:text="Button1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"/>
    

</TableLayout>

但是,最后呈现的效果居然是按钮一人占据了一整行,跟wrap_content的效果截然不同,反而更像match_parent
在这里插入图片描述
这也正是表格布局的特点之一,直接加入控件的时候每个控件都会占据一行,如下图:
在这里插入图片描述
如果想要在一行中加入多个按钮,则需要使用<TableRow></TableRow>将要放到一行的组件框起来:

<TableRow>
        <Button
            android:text="Button1"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>

        <Button
            android:text="Button2"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>
    </TableRow>

在这里插入图片描述
可以看到被框住的两个按钮被放在了同一行,且按钮变回了wrap_content该有的大小。

同时,由于限制在了同一行,当组件宽度超过屏幕宽度时,表格布局不会换行,而是直接不显示超出的部分,如下图:
在这里插入图片描述

常见属性

android:collapseColumns 设置需要被隐藏的列的序号,从0开始
android:stretchColumns 设置允许被拉伸的列的序号,从0开始
android:shrinkColumns 设置允许被收缩的列的序号,从0开始

android:layout_column 设置子控件显示在第几列
android:layout_span 设置子控件横跨几列

隐藏第0列和第2列:

android:collapseColumns="0,2"

在这里插入图片描述
设置某列拉伸可以让该列占据这一行的剩余空间,前提是改行有空余位置,如在隐藏第0、2列时拉伸第1列:

android:stretchColumns="1"

在这里插入图片描述
不隐藏第0、2列导致没有剩余空间时拉伸:
在这里插入图片描述
跟拉伸相反,在有超出部分的时候使用收缩,可以让压缩对应空间使得一整行的组件都能被屏幕显示。

android:shrinkColumns="1,3"

在这里插入图片描述

第一个组件都是默认在第0列显示的,在其后面的组件的列序号顺延,而layout_column可以设置该组件的列序号。

<TableRow>
        <Button
            android:text="Button1"
            android:layout_height="wrap_content"
            android:layout_column="1"
            android:layout_width="wrap_content"/>

        <Button
            android:text="Button2"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>
    </TableRow>

在这里插入图片描述
如果一个组件不满足于仅占用一列,可以设置layout_span使其跨多列显示。

<TableRow>
        <Button
            android:text="Button1"
            android:layout_height="wrap_content"
            android:layout_column="1"
            android:layout_span="2"
            android:layout_width="wrap_content"/>

        <Button
            android:text="Button2"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>
    </TableRow>

在这里插入图片描述

举报

相关推荐

0 条评论