Android问题集(七)——TableLayout 中让TableRow中的控件填充满整列

本文介绍了在Android开发中遇到的TableLayout中TableRow控件无法填充满整列的问题。通过分析代码和TableLayout的特性,提出了解决方案:使用`android:stretchColumns`属性来指定需要拉伸的列,从而使按钮能完全填充表格列宽。设置该属性后,显示效果达到预期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用情景:TableLayout、TableRow及其内的button控件width都设为android:layout_width="match_parent",但button不填充满宽度,实际显示如下:
这里写图片描述


代码如下

<?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" 
    >

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        >

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent" 
                />

    </TableRow>
</TableLayout>

原因:在表格布局中,列默认不可拉伸,即使设置android:layout_width="match_parent",显示效果为上图。若要使列控件填充整行,则在TableLayout属性中配置android:stretchColumns=""


android:stretchColumns属性
功能:设置允许被拉伸的列的序列号(序列号从0开始),多个序列号中间用“,”分隔。


如上的代码只需在TableLayout中增加属性android:stretchColumns="0"即可,效果如下:
这里写图片描述


更改后代码如下:

<?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" 
    android:stretchColumns="0">

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        >

            <Button
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                />


    </TableRow>

</TableLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值