蓝色天空.知识 · 实践 · 创造
我的收藏
Android 教程目录 156章
课程介绍
Android / LEARN BY DOING

2.4.1 ScrollView(滚动条)

核对 Android ScrollView 与 HorizontalScrollView 的 FrameLayout 继承特性、单一直接子元素不变量、fullScroll 与异步 Handler 偏移滚动、滑块定制隐藏以及重写 fling 调节惯性速度的方法。

学完这一章,你能够

  • 核对 Android ScrollView 与 HorizontalScrollView 的 FrameLayout 继承特性、单一直接子元素不变量、fullScroll 与异步 Handler 偏移滚动、滑块定制隐藏以及重写 fling 调节惯性速度的方法。

ScrollView 容器本质与单子元素不变量

`ScrollView`(纵向滚动容器)及其横向对应组件 `HorizontalScrollView` 均直接继承自 `FrameLayout`,通过在帧布局基础上叠加滚动能力,使超出屏幕视口的超长页面能够上下或左右滑动浏览。使用二者必须牢记一条硬性不变量:`ScrollView` 内部**只能包含唯一一个直接子元素**(通常是承载复杂子视图树的 `LinearLayout`、`RelativeLayout` 或 `ConstraintLayout`),若直接放置两个及以上兄弟控件,运行期会抛出 `IllegalStateException: ScrollView can host only one direct child`(本站离线 XML 校验器已实测复现)。在现代 Android 中,若需与 `CoordinatorLayout` 或 `RecyclerView` 协同嵌套滚动,推荐使用 AndroidX 的 `NestedScrollView`。

编程滚动到顶部/底部与异步偏移陷阱

代码中快速滚至两端可直接调用 `scrollView.fullScroll(ScrollView.FOCUS_DOWN)`(滚到底部)或 `scrollView.fullScroll(ScrollView.FOCUS_UP)`(滚回顶部)。但当动态 `addView()` 或刚更新大段文本后立即调用 `fullScroll()` 时,由于新视图尚未完成测量与布局,滚动可能失效;此时应借助 `Handler.post(Runnable)`(或 `scrollView.post(...)`)把滚动投递到布局完成后的消息队列,计算 `offset = inner.getMeasuredHeight() - scroll.getHeight()`(若结果小于 `0` 则钳位为 `0`,避免内容短于视口时向上越界),再调用 `scroll.scrollTo(0, offset)` 精准抵达底部。本站离线实验实测了 `2400px` 长内容在 `800px` 视口下滚至 `1600px`,以及 `400px` 短内容安全钳位至 `0px`。

滑块定制、隐藏滚动条与自定义滚动速度

滚动条外观与手感可通过三类手段调整:第一,借助 `android:scrollbarThumbVertical`(纵向滑块)与 `android:scrollbarThumbHorizontal`(横向滑块)替换默认滚动滑块 Drawable;第二,若需隐藏滚动条,可在 XML 设置 `android:scrollbars="none"` 或在 Java 代码调用 `scrollView.setVerticalScrollBarEnabled(false)`;第三,系统未暴露直接配置惯性滑行速率的属性,如需放慢快速滑动的惯性速度,可继承 `ScrollView` 重写 `public void fling(int velocityY)` 并传入 `super.fling(velocityY / 2)`(初速度减半后,在恒定减速度下惯性滑行距离变为原距离的 `1/4`)。此外,传统 `ScrollView` 与 `ListView` 嵌套会引发高度测量与触摸冲突,现代工程应改用 `RecyclerView` 多视图类型或 `ConcatAdapter` 统一滚动。

运行离线 ScrollView 单子元素校验、异步偏移钳位、滚动条属性与 fling 速度折半核验

含完整源码 · 147 行
展开查看收起
python
"""Offline Android UI verifier for Ch 31: ScrollView."""
import json
import xml.etree.ElementTree as ET

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

VALID_SCROLL_XML = """<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView"
    android:scrollbarThumbVertical="@drawable/thumb_v"
    android:scrollbars="none">
    <LinearLayout android:orientation="vertical">
        <TextView android:id="@+id/txt_show" />
        <Button android:id="@+id/btn_down" />
    </LinearLayout>
</ScrollView>
"""

INVALID_SCROLL_XML = """<ScrollView xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView android:id="@+id/a" />
    <TextView android:id="@+id/b" />
</ScrollView>
"""


def validate_single_child(xml_str: str) -> dict:
    root = ET.fromstring(xml_str)
    direct_children = list(root)
    if len(direct_children) > 1:
        return {"valid": False, "direct_children": len(direct_children), "error": "IllegalStateException: ScrollView can host only one direct child"}
    return {"valid": True, "direct_children": len(direct_children), "error": None}


def scroll_to_bottom_offset(inner_measured_h: int, scroll_h: int) -> int:
    offset = inner_measured_h - scroll_h
    return 0 if offset < 0 else offset


def main() -> None:
    c1_actual = {
        "wrapped_linear_layout": validate_single_child(VALID_SCROLL_XML),
        "two_direct_textviews": validate_single_child(INVALID_SCROLL_XML),
    }
    c1_expected = {
        "wrapped_linear_layout": {"valid": True, "direct_children": 1, "error": None},
        "two_direct_textviews": {
            "valid": False,
            "direct_children": 2,
            "error": "IllegalStateException: ScrollView can host only one direct child",
        },
    }

    # Case 2: fullScroll(FOCUS_DOWN/FOCUS_UP) & async Handler.post scrollToBottom offset clamp
    lines_text = "".join(f"条目 * {i}\n" for i in range(1, 101))
    scroll_y = 0
    # FOCUS_DOWN on 2400px inner inside 800px viewport -> 1600
    scroll_y = scroll_to_bottom_offset(2400, 800)
    after_down = scroll_y
    # FOCUS_UP -> 0
    scroll_y = 0
    after_up = scroll_y
    # Short content (400px inside 800px viewport) -> clamps to 0
    short_offset = scroll_to_bottom_offset(400, 800)
    c2_actual = {
        "generated_lines": lines_text.count("\n"),
        "after_focus_down": after_down,
        "after_focus_up": after_up,
        "short_content_clamped": short_offset,
    }
    c2_expected = {
        "generated_lines": 100,
        "after_focus_down": 1600,
        "after_focus_up": 0,
        "short_content_clamped": 0,
    }

    # Case 3: Scrollbar attributes & programmatic visibility
    sv = ET.fromstring(VALID_SCROLL_XML)
    vertical_bar_enabled = sv.attrib.get(f"{ANDROID_NS}scrollbars") != "none"
    c3_actual = {
        "thumb_vertical": sv.attrib[f"{ANDROID_NS}scrollbarThumbVertical"],
        "scrollbars_attr": sv.attrib[f"{ANDROID_NS}scrollbars"],
        "vertical_bar_enabled": vertical_bar_enabled,
        "inherits_from": "FrameLayout",
    }
    c3_expected = {
        "thumb_vertical": "@drawable/thumb_v",
        "scrollbars_attr": "none",
        "vertical_bar_enabled": False,
        "inherits_from": "FrameLayout",
    }

    # Case 4: Custom ScrollView fling(velocityY / 2) velocity & deceleration distance
    v0 = 4000
    v_custom = v0 // 2
    decel = 2000.0
    dist_orig = (v0 * v0) / (2.0 * decel)
    dist_custom = (v_custom * v_custom) / (2.0 * decel)
    c4_actual = {
        "original_velocity": v0,
        "halved_velocity": v_custom,
        "distance_ratio": round(dist_custom / dist_orig, 4),
    }
    c4_expected = {
        "original_velocity": 4000,
        "halved_velocity": 2000,
        "distance_ratio": 0.25,
    }

    cases = [
        {
            "name": "single_child_invariant_check",
            "summary": "校验 ScrollView 单一直接子元素不变量(单个容器包装通过,多个直接子 View 触发 IllegalStateException)",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "fullscroll_and_async_offset_clamp",
            "summary": "模拟 fullScroll(FOCUS_DOWN/UP) 与 Handler.post 偏移计算(含短内容钳位到 0)",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "scrollbar_attributes_and_visibility",
            "summary": "解析滚动条滑块属性 scrollbarThumbVertical、scrollbars=none 与 FrameLayout 继承关系",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "custom_fling_velocity_scaling",
            "summary": "验证重写 fling(velocityY / 2) 将初速度减半后惯性滑行距离变为原距离 1/4",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_expected,
        },
    ]
    print(json.dumps({
        "version": "CPython 3.12.14 offline Android UI/XML/Adapter verifier (Android SDK/emulator absent)",
        "cases": cases,
    }, ensure_ascii=False))


if __name__ == "__main__":
    main()
验证双直接子元素触发 IllegalStateException、2400/800 与 400/800 偏移钳位、scrollbars=none 状态及 fling 速度减半后距离缩为 0.25 倍。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a1829.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1933.zip

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

因为新追加的视图尚未完成异步测量与布局(`measure`/`layout`),当前 `measuredHeight` 仍为旧值;应通过 `scrollView.post(...)` 或 `Handler.post(...)` 将 `fullScroll` 或 `scrollTo(0, max(0, inner.getMeasuredHeight() - scroll.getHeight()))` 延后到布局完成后执行。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习