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

运行 OnTouchListener vs onTouchEvent 优先级、多点动作掩码与 Matrix 拖动缩放离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-touchlistener-ontouchevent.py
explore-tutorial-touchlistener-ontouchevent.py213 行
"""Offline Android verifier for Ch58: OnTouchListener vs onTouchEvent & Multi-Touch Matrix."""
import json
import math
from dataclasses import dataclass

ACTION_MASK = 0xFF
ACTION_DOWN = 0
ACTION_UP = 1
ACTION_MOVE = 2
ACTION_POINTER_DOWN = 5
ACTION_POINTER_UP = 6


@dataclass
class MotionEvent:
    raw_action: int
    pointers: list[tuple[float, float]]

    @property
    def action_masked(self) -> int:
        return self.raw_action & ACTION_MASK

    @property
    def pointer_count(self) -> int:
        return len(self.pointers)

    def get_x(self, index: int = 0) -> float:
        return self.pointers[index][0]

    def get_y(self, index: int = 0) -> float:
        return self.pointers[index][1]


def dispatch_touch_on_view(listener_returns: bool | None, view_on_touch_event_returns: bool) -> list[str]:
    calls: list[str] = []
    if listener_returns is not None:
        calls.append("OnTouchListener.onTouch")
        if listener_returns:
            return calls
    calls.append("View.onTouchEvent")
    if not view_on_touch_event_returns:
        calls.append("Activity.onTouchEvent")
    return calls


@dataclass
class Affine2D:
    # 2D scale + translate matrix: x' = sx * x + tx, y' = sy * y + ty
    sx: float = 1.0
    sy: float = 1.0
    tx: float = 0.0
    ty: float = 0.0

    def copy(self) -> "Affine2D":
        return Affine2D(self.sx, self.sy, self.tx, self.ty)

    def post_translate(self, dx: float, dy: float) -> None:
        self.tx += dx
        self.ty += dy

    def post_scale(self, scale: float, px: float, py: float) -> None:
        self.sx *= scale
        self.sy *= scale
        self.tx = scale * (self.tx - px) + px
        self.ty = scale * (self.ty - py) + py

    def rounded(self) -> list[float]:
        return [round(self.sx, 4), round(self.sy, 4), round(self.tx, 4), round(self.ty, 4)]


def main() -> None:
    # Case 1: OnTouchListener vs onTouchEvent dispatch precedence
    act1 = {
        "listener_true": dispatch_touch_on_view(True, True),
        "listener_false_view_true": dispatch_touch_on_view(False, True),
        "listener_false_view_false": dispatch_touch_on_view(False, False),
    }
    exp1 = {
        "listener_true": ["OnTouchListener.onTouch"],
        "listener_false_view_true": ["OnTouchListener.onTouch", "View.onTouchEvent"],
        "listener_false_view_false": ["OnTouchListener.onTouch", "View.onTouchEvent", "Activity.onTouchEvent"],
    }

    # Case 2: Custom MyView circle tracking (X, Y) + invalidate count
    cx, cy = 50.0, 50.0
    invalidations = 0
    for ev in [
        MotionEvent(ACTION_DOWN, [(120.0, 180.0)]),
        MotionEvent(ACTION_MOVE, [(165.0, 210.0)]),
        MotionEvent(ACTION_UP, [(200.0, 250.0)]),
    ]:
        cx, cy = ev.get_x(), ev.get_y()
        invalidations += 1
    act2 = {"final_center": [cx, cy], "radius": 30, "invalidations": invalidations}
    exp2 = {"final_center": [200.0, 250.0], "radius": 30, "invalidations": 3}

    # Case 3: Multi-touch pointer lifecycle & ACTION_MASK decoding
    raw_events = [
        MotionEvent(ACTION_DOWN, [(100.0, 100.0)]),
        MotionEvent((1 << 8) | ACTION_POINTER_DOWN, [(100.0, 100.0), (200.0, 100.0)]),
        MotionEvent(ACTION_MOVE, [(100.0, 100.0), (300.0, 100.0)]),
        MotionEvent((1 << 8) | ACTION_POINTER_UP, [(100.0, 100.0), (300.0, 100.0)]),
        MotionEvent(ACTION_UP, [(100.0, 100.0)]),
    ]
    decoded = [(e.action_masked, e.pointer_count) for e in raw_events]
    act3 = {"decoded_sequence": [list(x) for x in decoded]}
    exp3 = {"decoded_sequence": [[0, 1], [5, 2], [2, 2], [6, 2], [1, 1]]}

    # Case 4: Single-finger DRAG & two-finger ZOOM Matrix transformations
    matrix = Affine2D()
    saved = matrix.copy()
    mode = "NONE"
    start_pt = (0.0, 0.0)
    mid_pt = (0.0, 0.0)
    ori_dis = 1.0

    def dist(e: MotionEvent) -> float:
        return math.hypot(e.get_x(0) - e.get_x(1), e.get_y(0) - e.get_y(1))

    def mid(e: MotionEvent) -> tuple[float, float]:
        return ((e.get_x(0) + e.get_x(1)) / 2.0, (e.get_y(0) + e.get_y(1)) / 2.0)

    # Drag from (100,100) to (140,160) -> tx=40, ty=60
    drag_stream = [
        MotionEvent(ACTION_DOWN, [(100.0, 100.0)]),
        MotionEvent(ACTION_MOVE, [(140.0, 160.0)]),
        MotionEvent(ACTION_UP, [(140.0, 160.0)]),
    ]
    # Zoom around midpoint (200, 100): ori_dis=100 -> new_dis=200 => scale=2.0
    zoom_stream = [
        MotionEvent(ACTION_DOWN, [(150.0, 100.0)]),
        MotionEvent((1 << 8) | ACTION_POINTER_DOWN, [(150.0, 100.0), (250.0, 100.0)]),
        MotionEvent(ACTION_MOVE, [(100.0, 100.0), (300.0, 100.0)]),
        MotionEvent((1 << 8) | ACTION_POINTER_UP, [(100.0, 100.0), (300.0, 100.0)]),
    ]

    snapshots = {}
    for label, stream in [("after_drag", drag_stream), ("after_zoom", zoom_stream)]:
        for ev in stream:
            act = ev.action_masked
            if act == ACTION_DOWN:
                saved = matrix.copy()
                start_pt = (ev.get_x(), ev.get_y())
                mode = "DRAG"
            elif act == ACTION_POINTER_DOWN:
                ori_dis = dist(ev)
                if ori_dis > 10.0:
                    saved = matrix.copy()
                    mid_pt = mid(ev)
                    mode = "ZOOM"
            elif act in (ACTION_UP, ACTION_POINTER_UP):
                mode = "NONE"
            elif act == ACTION_MOVE:
                if mode == "DRAG":
                    matrix = saved.copy()
                    matrix.post_translate(ev.get_x() - start_pt[0], ev.get_y() - start_pt[1])
                elif mode == "ZOOM":
                    new_dis = dist(ev)
                    if new_dis > 10.0:
                        matrix = saved.copy()
                        matrix.post_scale(new_dis / ori_dis, mid_pt[0], mid_pt[1])
        snapshots[label] = matrix.rounded()

    exp4 = {
        "after_drag": [1.0, 1.0, 40.0, 60.0],
        "after_zoom": [2.0, 2.0, -120.0, 20.0],
    }

    cases = [
        {
            "name": "touch_listener_vs_ontouchevent_precedence",
            "summary": "验证 OnTouchListener.onTouch 返回 true 时先于 onTouchEvent 消费事件,返回 false 则继续回调",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        },
        {
            "name": "custom_view_circle_drag_invalidation",
            "summary": "验证自定义 MyView 在 onTouchEvent 更新圆心坐标并触发 invalidate 重绘次数",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        },
        {
            "name": "multitouch_action_mask_and_pointer_count",
            "summary": "验证 ACTION_MASK 解析多指按下/移动/抬起动作码及 getPointerCount 触点数演变",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        },
        {
            "name": "matrix_single_drag_and_pinch_zoom",
            "summary": "验证单指 DRAG(postTranslate) 与双指 ZOOM(postScale 围绕中点缩放 2 倍) 矩阵结果",
            "expected": exp4,
            "actual": snapshots,
            "passed": snapshots == 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-touchlistener-ontouchevent-lab/explore-tutorial-touchlistener-ontouchevent.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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