You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android TableLayout的TableRow中居中并拉伸按钮适配表单宽度

问题原因

你当前布局的问题由两个原因导致:

  1. 前两行TableRow均为2列结构,第三行的Button默认只占用第0列,未跨列适配整行宽度
  2. 你仅设置拉伸第1列,同时TableLayout添加了android:gravity="center"属性,会限制子控件的拉伸效果

修改步骤

  • 删除TableLayout的android:gravity="center"属性,添加android:stretchColumns="*"属性,让所有列都支持按规则拉伸
  • 给第三行的Button添加android:layout_span="2"属性,指定按钮跨2列展示
  • 可按需调整Button的左右边距,和上方输入框的边距对齐,保证视觉统一

修改后完整代码

<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="*"
    tools:context=".MainActivity">

    <TableRow>
        <TextView
            android:layout_weight="0.5"
            android:text="Login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp"
            android:layout_marginStart="50dp"/>

        <EditText
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="25dp"
            android:layout_marginEnd="25dp"
        />
    </TableRow>

    <TableRow>
        <TextView
            android:layout_weight="0.5"
            android:text="Email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp"
            android:layout_marginStart="50dp"
        />

        <EditText
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="25dp"
            android:layout_marginEnd="25dp"
        />
    </TableRow>

    <TableRow>
        <Button
            android:text="Send"
            android:layout_span="2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="25dp"
        />
    </TableRow>
</TableLayout>

如果需要按钮左右留边和上方输入框对齐,保留代码里的android:layout_marginHorizontal="25dp"即可,不需要的话删除该属性就能让按钮完全占满整行宽度。


内容的提问来源于stack exchange,提问作者whoamins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 15:36:06