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

运行 PopupWindow 定位计算、API 21 背景关闭契约与触摸拦截离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-popupwindow.py
explore-tutorial-popupwindow.py164 行
"""Offline Android verifier for Ch51: PopupWindow positioning, focus/background dismiss & touch interceptor."""
import json
import xml.etree.ElementTree as ET

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


class MockPopupWindow:
    def __init__(self, width: str, height: str, focusable: bool = False):
        self.width = width
        self.height = height
        self.focusable = focusable
        self.touchable = True
        self.background_drawable: str | None = None
        self.touch_interceptor = None
        self.showing = False
        self.pos = (0, 0)

    def show_as_drop_down(self, anchor_rect: tuple[int, int, int, int], xoff: int = 0, yoff: int = 0) -> None:
        left, _top, _right, bottom = anchor_rect
        self.pos = (left + xoff, bottom + yoff)
        self.showing = True

    def show_at_location(self, parent_size: tuple[int, int], gravity: str, x: int = 0, y: int = 0) -> None:
        pw, ph = parent_size
        if gravity == "CENTER":
            self.pos = (pw // 2 + x, ph // 2 + y)
        elif gravity == "BOTTOM":
            self.pos = (pw // 2 + x, ph + y)
        else:
            self.pos = (x, y)
        self.showing = True

    def dispatch_outside_touch(self, api_level: int = 21) -> dict:
        if not self.showing:
            return {"dismissed": False, "intercepted": False}
        if self.touch_interceptor is not None and self.touch_interceptor("OUTSIDE"):
            return {"dismissed": False, "intercepted": True}
        # Prior to API 23 (Android 6.0), PopupWindow requires non-null background for outside/back dismiss
        can_dismiss = self.focusable and (api_level >= 23 or self.background_drawable is not None)
        if can_dismiss:
            self.showing = False
        return {"dismissed": can_dismiss, "intercepted": False}

    def press_back(self, api_level: int = 21) -> str:
        if not self.showing:
            return "exit_activity"
        if self.focusable and (api_level >= 23 or self.background_drawable is not None):
            self.showing = False
            return "dismiss_popup"
        return "blocked_no_background"


def main() -> None:
    # Case 1: showAsDropDown & showAtLocation coordinate positioning
    pop = MockPopupWindow("WRAP_CONTENT", "WRAP_CONTENT", focusable=True)
    pop.show_as_drop_down((100, 200, 300, 260), xoff=50, yoff=0)
    dropdown_pos = list(pop.pos)
    pop.show_at_location((1080, 1920), "CENTER", x=0, y=-40)
    center_pos = list(pop.pos)
    act1 = {"dropdown_pos": dropdown_pos, "center_pos": center_pos}
    exp1 = {"dropdown_pos": [150, 260], "center_pos": [540, 920]}

    # Case 2: Background drawable + focusable Back-key / outside-touch dismiss on API 21
    pop_no_bg = MockPopupWindow("WRAP_CONTENT", "WRAP_CONTENT", focusable=True)
    pop_no_bg.show_as_drop_down((0, 0, 100, 50))
    back_without_bg = pop_no_bg.press_back(api_level=21)
    outside_without_bg = pop_no_bg.dispatch_outside_touch(api_level=21)

    pop_with_bg = MockPopupWindow("WRAP_CONTENT", "WRAP_CONTENT", focusable=True)
    pop_with_bg.background_drawable = "ColorDrawable(0x00000000)"
    pop_with_bg.show_as_drop_down((0, 0, 100, 50))
    first_back = pop_with_bg.press_back(api_level=21)
    second_back = pop_with_bg.press_back(api_level=21)
    act2 = {
        "back_without_bg": back_without_bg,
        "outside_without_bg": outside_without_bg["dismissed"],
        "first_back_with_bg": first_back,
        "second_back_with_bg": second_back,
    }
    exp2 = {
        "back_without_bg": "blocked_no_background",
        "outside_without_bg": False,
        "first_back_with_bg": "dismiss_popup",
        "second_back_with_bg": "exit_activity",
    }

    # Case 3: setTouchInterceptor returning true vs false
    pop_int = MockPopupWindow("WRAP_CONTENT", "WRAP_CONTENT", focusable=True)
    pop_int.background_drawable = "ColorDrawable(0x00000000)"
    pop_int.show_as_drop_down((0, 0, 100, 50))
    pop_int.touch_interceptor = lambda ev: True
    res_true = pop_int.dispatch_outside_touch(api_level=21)
    pop_int.touch_interceptor = lambda ev: False
    res_false = pop_int.dispatch_outside_touch(api_level=21)
    act3 = {"when_true": res_true, "when_false": res_false, "showing_after": pop_int.showing}
    exp3 = {
        "when_true": {"dismissed": False, "intercepted": True},
        "when_false": {"dismissed": True, "intercepted": False},
        "showing_after": False,
    }

    # Case 4: Alpha animation & PopupWindow content layout XML parsing
    anim_xml = '<set xmlns:android="http://schemas.android.com/apk/res/android"><alpha android:fromAlpha="0" android:toAlpha="1" android:duration="2000" /></set>'
    layout_xml = """
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical">
        <Button android:id="@+id/btn_xixi" android:text="嘻嘻" />
        <Button android:id="@+id/btn_hehe" android:text="呵呵" />
    </LinearLayout>
    """
    alpha = ET.fromstring(anim_xml).find("alpha")
    btns = [b.attrib[ANDROID_NS + "text"] for b in ET.fromstring(layout_xml).findall("Button")]
    act4 = {
        "alpha_range": [int(alpha.attrib[ANDROID_NS + "fromAlpha"]), int(alpha.attrib[ANDROID_NS + "toAlpha"])],
        "duration_ms": int(alpha.attrib[ANDROID_NS + "duration"]),
        "buttons": btns,
    }
    exp4 = {"alpha_range": [0, 1], "duration_ms": 2000, "buttons": ["嘻嘻", "呵呵"]}

    cases = [
        {
            "name": "popup_anchor_and_gravity_positioning",
            "summary": "验证 showAsDropDown(anchor, 50, 0) 与 showAtLocation(CENTER) 悬浮坐标计算",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        },
        {
            "name": "focusable_and_background_dismiss_contract",
            "summary": "验证 Android 6.0 以下设置 ColorDrawable 背景对 Back 键与外部点击关闭 PopupWindow 的必要性",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        },
        {
            "name": "touch_interceptor_consumption_behavior",
            "summary": "验证 setTouchInterceptor 返回 true 拦截外部触摸导致无法 dismiss,返回 false 正常关闭",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        },
        {
            "name": "popup_alpha_anim_and_layout_xml",
            "summary": "解析 anim_pop.xml 透明度渐变参数与悬浮框双按钮布局 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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

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

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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