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

如何在RelativeLayout中实现TableLayout表头固定、表格行可滚动的效果

固定表头可滚动表格实现方案

实现逻辑

  • 拆分原有表格结构:将表头行单独抽离为固定模块,位置不会跟随滚动变化
  • 所有数据行放入独立的TableLayout中,外层嵌套ScrollView实现内容滚动
  • 表头和数据行的列配置(layout_width、layout_weight)保持完全一致,避免出现列不对齐的问题

修改后的完整布局代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:padding="40dp"
    android:background="@android:color/white">

    <!-- 固定表头部分 -->
    <TableLayout
        android:id="@+id/table_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TableRow
            android:layout_height="47dp"
            android:background="@color/colorGreen">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:gravity="center_horizontal"
                android:padding="10sp"
                android:text="Department"
                android:textColor="@android:color/white"
                android:textSize="14sp" />
        </TableRow>
    </TableLayout>

    <!-- 可滚动的内容部分 -->
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/table_header">

        <TableLayout
            android:id="@+id/table_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TableRow>
                <TextView
                    android:text="B.E/B.Tech"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="2"
                    android:gravity="center_horizontal"
                    android:padding="10sp"
                    android:textSize="15sp" />
            </TableRow>
            <TableRow>
                <TextView
                    android:text="M.E/M.Tech"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="2"
                    android:gravity="center_horizontal"
                    android:padding="10sp"
                    android:textSize="15sp" />
                <!-- 后续新增的表格行都放在这个TableLayout内即可 -->
            </TableRow>
        </TableLayout>
    </ScrollView>

</RelativeLayout>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:15:03