GridLayout:网格布局 · AndroidX 源码指南
AAndroidX 源码指南
View 体系
View 体系 · androidx.core

GridLayout:网格布局Core 1.20.0-alpha01

用 rowCount/columnCount 与权重表达网格,替代嵌套 LinearLayout。

最后更新 2026-08-01

复制即用

<androidx.gridlayout.widget.GridLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:columnCount="3"
    app:rowCount="2">

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_columnWeight="1"
        android:text="A" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_columnWeight="1"
        android:text="B" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_columnWeight="1"
        android:text="C" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_columnWeight="1"
        app:layout_columnSpan="3"
        android:text="整行按钮" />
</androidx.gridlayout.widget.GridLayout>

代码控制:

import androidx.gridlayout.widget.GridLayout;

GridLayout grid = findViewById(R.id.grid);
grid.setColumnCount(3);
grid.setRowCount(2);

常见陷阱

  • width/height 设成 0dp + weight:等分列需要 layout_width="0dp" + layout_columnWeight,否则按内容宽。
  • rowCount/columnCount 过小:子 View 超出网格会自动扩展,但显式声明更可预测。
  • Span 越界layout_columnSpan 超出 columnCount 会异常。
  • 嵌套 GridLayout:避免,用 span/weight 表达更扁平的结构。

要点

  • 通过 columnCount/rowCount 定义网格规模,子 View 自动排列或显式指定 layout_row/layout_column
  • layout_columnSpan/layout_rowSpan 合并单元格;layout_columnWeight 让列等宽分配。
  • 相比嵌套多层 LinearLayout 更扁平、测量更高效。
  • Compose 中对应 LazyVerticalGridGridCells.Fixed,View 场景用此库。

相关页面