蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 ViewFlipper 自动循环轮播、onFling 双向手势切页与动画 XML 离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-viewflipper.py
explore-tutorial-viewflipper.py171 行
"""Offline Android verifier for Ch46: ViewFlipper circular slides, animations & fling gesture."""
import json
import xml.etree.ElementTree as ET

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


class MockViewFlipper:
    def __init__(self, flip_interval_ms: int = 3000):
        self.views: list[str] = []
        self.current_index = 0
        self.flip_interval_ms = flip_interval_ms
        self.flipping = False
        self.in_anim: str | None = None
        self.out_anim: str | None = None

    def add_view(self, name: str) -> None:
        self.views.append(name)

    def set_in_animation(self, anim: str) -> None:
        self.in_anim = anim

    def set_out_animation(self, anim: str) -> None:
        self.out_anim = anim

    def show_next(self) -> str:
        self.current_index = (self.current_index + 1) % len(self.views)
        return self.views[self.current_index]

    def show_previous(self) -> str:
        self.current_index = (self.current_index - 1) % len(self.views)
        return self.views[self.current_index]

    def start_flipping(self) -> None:
        self.flipping = True

    def stop_flipping(self) -> None:
        self.flipping = False

    def advance_clock(self, elapsed_ms: int) -> list[str]:
        if not self.flipping or not self.views:
            return []
        steps = elapsed_ms // self.flip_interval_ms
        return [self.show_next() for _ in range(steps)]


def handle_fling(vf: MockViewFlipper, x1: float, x2: float, min_move: float = 200.0) -> dict:
    if x1 - x2 > min_move:
        vf.set_in_animation("right_in")
        vf.set_out_animation("right_out")
        shown = vf.show_next()
        direction = "next"
    elif x2 - x1 > min_move:
        vf.set_in_animation("left_in")
        vf.set_out_animation("left_out")
        shown = vf.show_previous()
        direction = "previous"
    else:
        shown = vf.views[vf.current_index]
        direction = "ignored"
    return {"direction": direction, "shown": shown, "in": vf.in_anim, "out": vf.out_anim}


def main() -> None:
    # Case 1: Static include & auto-flip circular wrap-around
    vf_static = MockViewFlipper(flip_interval_ms=3000)
    for page in ("page_help_one", "page_help_two", "page_help_three", "page_help_four"):
        vf_static.add_view(page)
    vf_static.set_in_animation("right_in")
    vf_static.set_out_animation("right_out")
    vf_static.start_flipping()
    seq = vf_static.advance_clock(15000)  # 5 ticks -> wraps around page 0
    vf_static.stop_flipping()
    after_stop = vf_static.advance_clock(6000)
    act1 = {"sequence": seq, "current_index": vf_static.current_index, "after_stop": after_stop}
    exp1 = {
        "sequence": ["page_help_two", "page_help_three", "page_help_four", "page_help_one", "page_help_two"],
        "current_index": 1,
        "after_stop": [],
    }

    # Case 2: Dynamic addView & GestureDetector onFling direction + MIN_MOVE threshold
    vf_dyn = MockViewFlipper()
    for i in range(1, 5):
        vf_dyn.add_view(f"ic_help_view_{i}")
    r_small = handle_fling(vf_dyn, 500, 380)  # delta 120 <= 200 -> ignored
    r_next = handle_fling(vf_dyn, 500, 200)   # delta 300 > 200 -> next (view 2)
    r_prev1 = handle_fling(vf_dyn, 200, 500)  # delta -300 -> prev (view 1)
    r_prev2 = handle_fling(vf_dyn, 100, 450)  # wraps to view 4
    act2 = {"small": r_small, "next": r_next, "prev1": r_prev1, "prev_wrap": r_prev2}
    exp2 = {
        "small": {"direction": "ignored", "shown": "ic_help_view_1", "in": None, "out": None},
        "next": {"direction": "next", "shown": "ic_help_view_2", "in": "right_in", "out": "right_out"},
        "prev1": {"direction": "previous", "shown": "ic_help_view_1", "in": "left_in", "out": "left_out"},
        "prev_wrap": {"direction": "previous", "shown": "ic_help_view_4", "in": "left_in", "out": "left_out"},
    }

    # Case 3: Naive ACTION_MOVE jitter vs single onFling trigger
    move_stream_xs = [500, 280, 260, 240, 220]
    naive_triggers = sum(1 for x in move_stream_xs[1:] if move_stream_xs[0] - x > 200)
    fling_triggers = 1 if (move_stream_xs[0] - move_stream_xs[-1] > 200) else 0
    act3 = {"naive_action_move_flips": naive_triggers, "on_fling_flips": fling_triggers}
    exp3 = {"naive_action_move_flips": 4, "on_fling_flips": 1}

    # Case 4: Animation XML deltas & durations audit
    anims = {
        "right_in": '<set xmlns:android="http://schemas.android.com/apk/res/android"><translate android:duration="2000" android:fromXDelta="100%p" android:toXDelta="0" /></set>',
        "right_out": '<set xmlns:android="http://schemas.android.com/apk/res/android"><translate android:duration="2000" android:fromXDelta="0" android:toXDelta="-100%p" /></set>',
        "left_in": '<set xmlns:android="http://schemas.android.com/apk/res/android"><translate android:duration="500" android:fromXDelta="-100%p" android:toXDelta="0" /></set>',
        "left_out": '<set xmlns:android="http://schemas.android.com/apk/res/android"><translate android:duration="500" android:fromXDelta="0" android:toXDelta="100%p" /></set>',
    }
    parsed = {}
    for name, src in anims.items():
        tr = ET.fromstring(src).find("translate")
        parsed[name] = [
            int(tr.attrib[ANDROID_NS + "duration"]),
            tr.attrib[ANDROID_NS + "fromXDelta"],
            tr.attrib[ANDROID_NS + "toXDelta"],
        ]
    exp4 = {
        "right_in": [2000, "100%p", "0"],
        "right_out": [2000, "0", "-100%p"],
        "left_in": [500, "-100%p", "0"],
        "left_out": [500, "0", "100%p"],
    }

    cases = [
        {
            "name": "static_auto_flip_circular_state",
            "summary": "验证 ViewFlipper 静态导入 4 页后按 3000ms 间隔循环轮播与 stopFlipping 停止行为",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        },
        {
            "name": "dynamic_views_and_onfling_swipe",
            "summary": "验证动态 addView 后通过 onFling 与 MIN_MOVE=200 阈值切换上一页/下一页及首尾回绕",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        },
        {
            "name": "action_move_jitter_vs_onfling",
            "summary": "对比直接处理 ACTION_MOVE 的抖动误触发与 GestureDetector.onFling 单次触发次数",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        },
        {
            "name": "translate_animation_xml_audit",
            "summary": "解析 4 个左右进出平移动画 XML 的持续时间与百分比位移起止值",
            "expected": exp4,
            "actual": parsed,
            "passed": parsed == 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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/android-tutorial-viewflipper-lab/explore-tutorial-viewflipper.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-viewflipper.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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