蓝色天空网mbsky.com · 知识 · 实践 · 创造Android · 本地阅读预览
教程 / 移动开发 / Android

2.5.2 GridView(网格视图)的基本使用

核对 GridView 与 AbsListView 的继承关系、列宽/间距/拉伸模式等核心 XML 属性,结合可复用通用 BaseAdapter 演示三列图标网格与点击事件处理。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

GridView 定位与核心 XML 属性

`GridView`(网格视图)与 `ListView` 同属 `AbsListView` 的直接子类,均采用 `Adapter` 驱动视图复用机制,区别在于 `GridView` 按二维行列网格排布子项,常见于九宫格导航、应用图标墙与手机相册。

在布局中配置 `GridView` 时,常用 6 个核心属性控制网格几何形态:`android:columnWidth` 指定单列宽度,`android:gravity` 控制单元格内组件对齐方式,`android:horizontalSpacing` 与 `android:verticalSpacing` 分别设置水平和垂直单元格间距,`android:numColumns` 设置每行列数(可为正整数或 `auto_fit` 自动适配),`android:stretchMode` 决定剩余水平空间的拉伸策略——可选 `none`(不拉伸)、`spacingWidth`(仅拉伸列间距)、`columnWidth`(仅拉伸列自身宽度,默认策略)与 `spacingWidthUniform`(同时均匀拉伸列间距与左右边距)。

三列图标网格示例与点击响应

借助前节构建的可复用泛型 `MyAdapter<T>`,实现一个三列图标网格非常简洁:先编写单元格布局 `item_grid_icon.xml`(在 `RelativeLayout` 中居中放置 `64dp×64dp` 的 `ImageView`,其下方通过 `layout_below` 排列 `TextView`),再定义封装图标资源 ID 与名称的实体类 `Icon.java`。

主布局 `activity_main.xml` 中放置 `GridView` 并设置 `android:numColumns="3"`;在 `MainActivity` 中填充 7 个 `Icon` 实例并实例化 `MyAdapter<Icon>` 绑定图文控件,再调用 `setOnItemClickListener()` 在点击单元格时弹出当前位置提示。现代项目中同类网格列表通常使用 `RecyclerView` 搭配 `GridLayoutManager` 实现,以获得更好的动画与异构跨列支持。本站离线 Python 脚本实测了 4 种 `stretchMode` 与 `auto_fit` 的列宽/间距数学分配、7 项 3 列网格的 3 行排布及点击坐标转换。

示例代码包与小结

原教程提供 `GridViewDemo1.zip` 供下载参考(受源站停采策略限制未联网抓取,已登记至 `reviewed_source_attachments`)。掌握 `GridView` 的核心属性与适配器绑定后,即可进一步扩展实现本地相册、功能宫格等常见界面。

运行 GridView 四种 stretchMode 几何分配、7 项三列适配器绑定与点击事件离线验证

python · 阅读源码
"""Offline Android verifier for Ch42: GridView layout, stretch modes & Adapter binding."""
import json
import math
import xml.etree.ElementTree as ET
from dataclasses import dataclass

ANDROID_NS = "{http://schemas.android.com/apk/res/android}"


@dataclass(frozen=True)
class Icon:
    icon_id: str
    name: str


def compute_grid_geometry(
    available_width: int,
    requested_col_width: int,
    h_spacing: int,
    num_columns: int | str,
    stretch_mode: str,
) -> dict[str, int]:
    if num_columns == "auto_fit":
        cols = max(1, (available_width + h_spacing) // (requested_col_width + h_spacing))
    else:
        cols = int(num_columns)

    space_left = available_width - cols * requested_col_width - (cols - 1) * h_spacing
    col_w = requested_col_width
    actual_spacing = h_spacing
    edge_pad = 0

    if space_left > 0:
        if stretch_mode == "none":
            pass
        elif stretch_mode == "columnWidth":
            col_w += space_left // cols
        elif stretch_mode == "spacingWidth":
            if cols > 1:
                actual_spacing += space_left // (cols - 1)
        elif stretch_mode == "spacingWidthUniform":
            delta = space_left // (cols + 1)
            actual_spacing += delta
            edge_pad = delta
        else:
            raise ValueError(f"Unknown stretchMode: {stretch_mode}")

    return {
        "cols": cols,
        "col_width": col_w,
        "h_spacing": actual_spacing,
        "edge_padding": edge_pad,
    }


def main() -> None:
    # Case 1: GridView stretchMode & AUTO_FIT geometry
    modes = {
        m: compute_grid_geometry(360, 90, 10, 3, m)
        for m in ("none", "columnWidth", "spacingWidth", "spacingWidthUniform")
    }
    auto_fit = compute_grid_geometry(360, 100, 10, "auto_fit", "columnWidth")
    act1 = {"modes": modes, "auto_fit": auto_fit}
    exp1 = {
        "modes": {
            "none": {"cols": 3, "col_width": 90, "h_spacing": 10, "edge_padding": 0},
            "columnWidth": {"cols": 3, "col_width": 113, "h_spacing": 10, "edge_padding": 0},
            "spacingWidth": {"cols": 3, "col_width": 90, "h_spacing": 45, "edge_padding": 0},
            "spacingWidthUniform": {"cols": 3, "col_width": 90, "h_spacing": 27, "edge_padding": 17},
        },
        "auto_fit": {"cols": 3, "col_width": 113, "h_spacing": 10, "edge_padding": 0},
    }

    # Case 2: Reusable BaseAdapter binding 7 Icons into 3-column grid
    icons = [Icon(f"mipmap/iv_icon_{i}", f"图标{i}") for i in range(1, 8)]
    cols = 3
    rows = math.ceil(len(icons) / cols)
    bound_cells = [
        {"pos": idx, "row": idx // cols, "col": idx % cols, "icon": ic.icon_id, "label": ic.name}
        for idx, ic in enumerate(icons)
    ]
    act2 = {"count": len(bound_cells), "rows": rows, "last_cell": bound_cells[-1]}
    exp2 = {
        "count": 7,
        "rows": 3,
        "last_cell": {"pos": 6, "row": 2, "col": 0, "icon": "mipmap/iv_icon_7", "label": "图标7"},
    }

    # Case 3: OnItemClickListener dispatch
    clicked_positions = [0, 4, 6]
    toasts = [f"你点击了~{p}~项" for p in clicked_positions]
    act3 = {"toasts": toasts, "grid_coords": [(p // cols, p % cols) for p in clicked_positions]}
    exp3 = {
        "toasts": ["你点击了~0~项", "你点击了~4~项", "你点击了~6~项"],
        "grid_coords": [(0, 0), (1, 1), (2, 0)],
    }

    # Case 4: XML layout parsing audit
    main_xml = """
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:padding="5dp">
        <GridView android:id="@+id/grid_photo" android:layout_width="match_parent"
                  android:layout_height="match_parent" android:numColumns="3" />
    </RelativeLayout>
    """
    item_xml = """
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:padding="5dp">
        <ImageView android:id="@+id/img_icon" android:layout_width="64dp" android:layout_height="64dp" />
        <TextView android:id="@+id/txt_icon" android:layout_below="@id/img_icon" android:textSize="18sp" />
    </RelativeLayout>
    """
    gv = ET.fromstring(main_xml).find("GridView")
    item_root = ET.fromstring(item_xml)
    img = item_root.find("ImageView")
    txt = item_root.find("TextView")
    act4 = {
        "numColumns": gv.attrib[ANDROID_NS + "numColumns"],
        "icon_size": [img.attrib[ANDROID_NS + "layout_width"], img.attrib[ANDROID_NS + "layout_height"]],
        "text_below": txt.attrib[ANDROID_NS + "layout_below"],
    }
    exp4 = {
        "numColumns": "3",
        "icon_size": ["64dp", "64dp"],
        "text_below": "@id/img_icon",
    }

    cases = [
        {
            "name": "grid_layout_geometry_stretch_modes",
            "summary": "验证 GridView 在 4 种 stretchMode 及 auto_fit 下的列宽与间距分配计算",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        },
        {
            "name": "reusable_adapter_icon_binding",
            "summary": "验证 7 个 Icon 实体在 3 列网格中的 3 行排布与 ViewHolder 绑定结果",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        },
        {
            "name": "grid_item_click_dispatch",
            "summary": "验证 OnItemClickListener 根据 position 计算行列坐标并生成提示文本",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        },
        {
            "name": "item_xml_attribute_audit",
            "summary": "解析 GridView 主布局与单元格布局 XML,核对列数、图标尺寸与相对定位属性",
            "expected": exp4,
            "actual": act4,
            "passed": act4 == exp4,
        },
    ]
    print(
        json.dumps(
            {
                "version": "CPython 3.12.14 offline Android UI/Event/Handler verifier (Android SDK/emulator absent)",
                "cases": cases,
            },
            ensure_ascii=False,
            indent=2,
        )
    )


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 验证 none/columnWidth/spacingWidth/spacingWidthUniform 与 auto_fit 宽度分配、7 项排布 3 行及点击行列定位。
运行 GridView 四种 stretchMode 几何分配、7 项三列适配器绑定与点击事件离线验证

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:c2dfa60c340745fcf730d822016c773d38acffedf4f1ea0a9a811e501a8bc921

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载2.5.2 GridView(网格视图)的基本使用实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:2bb13e8f0d3fe64cb9b95d862ff0630518c7f9f28d23417b73767efe4ae6391c

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

GridView 的 android:stretchMode 属性中,spacingWidth 与 spacingWidthUniform 有何区别?

展开参考解答

spacingWidth 只把剩余水平空间分配到列与列之间的间隔中,而 spacingWidthUniform 会把剩余空间均匀分配到所有列间距以及网格左右两侧外边距中。

规范与官方依据