"""Offline Android verifier for Ch54: DrawerLayout gravity, lock modes & Fragment routing."""
import json
import xml.etree.ElementTree as ET
ANDROID_NS = "{http://schemas.android.com/apk/res/android}"
LOCK_MODE_UNLOCKED = 0
LOCK_MODE_LOCKED_CLOSED = 1
LOCK_MODE_LOCKED_OPEN = 2
class MockDrawerLayout:
def __init__(self, drawers: dict[str, dict]):
self.drawers = {g: dict(info, open=False, lock=LOCK_MODE_UNLOCKED) for g, info in drawers.items()}
self.events: list[str] = []
self.on_closed_cb = None
def set_lock_mode(self, mode: int, gravity: str) -> None:
self.drawers[gravity]["lock"] = mode
def swipe_open(self, gravity: str) -> bool:
d = self.drawers[gravity]
if d["lock"] == LOCK_MODE_LOCKED_CLOSED:
return False
d["open"] = True
self.events.append(f"opened:{d['tag']}")
return True
def open_drawer_programmatic(self, gravity: str) -> None:
# Programmatic openDrawer works even when LOCK_MODE_LOCKED_CLOSED
d = self.drawers[gravity]
d["open"] = True
self.events.append(f"prog_opened:{d['tag']}")
def swipe_close(self, gravity: str) -> bool:
d = self.drawers[gravity]
if d["lock"] in (LOCK_MODE_LOCKED_CLOSED, LOCK_MODE_LOCKED_OPEN):
return False
d["open"] = False
self.events.append(f"closed:{d['tag']}")
if self.on_closed_cb:
self.on_closed_cb(gravity)
return True
def close_drawer_programmatic(self, gravity: str) -> None:
d = self.drawers[gravity]
d["open"] = False
self.events.append(f"prog_closed:{d['tag']}")
if self.on_closed_cb:
self.on_closed_cb(gravity)
def audit_drawer_xml(xml_text: str) -> dict:
root = ET.fromstring(xml_text)
children = list(root)
main = children[0]
drawers = []
for ch in children[1:]:
w = ch.attrib.get(ANDROID_NS + "layout_width", "")
dp_val = int(w[:-2]) if w.endswith("dp") else 999
drawers.append(
{
"gravity": ch.attrib.get(ANDROID_NS + "layout_gravity"),
"width_dp": dp_val,
"within_320dp": dp_val <= 320,
"tag": ch.attrib.get(ANDROID_NS + "tag"),
}
)
return {
"main_is_match_parent": (
main.attrib.get(ANDROID_NS + "layout_width") == "match_parent"
and main.attrib.get(ANDROID_NS + "layout_height") == "match_parent"
),
"drawers": drawers,
}
def main() -> None:
# Case 1: DrawerLayout XML structural constraints audit
dual_xml = """
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" />
<fragment android:id="@+id/fg_left_menu" android:layout_width="300dp"
android:layout_gravity="start" android:tag="LEFT" />
<fragment android:id="@+id/fg_right_menu" android:layout_width="100dp"
android:layout_gravity="end" android:tag="RIGHT" />
</android.support.v4.widget.DrawerLayout>
"""
act1 = audit_drawer_xml(dual_xml)
exp1 = {
"main_is_match_parent": True,
"drawers": [
{"gravity": "start", "width_dp": 300, "within_320dp": True, "tag": "LEFT"},
{"gravity": "end", "width_dp": 100, "within_320dp": True, "tag": "RIGHT"},
],
}
# Case 2: Single-drawer ListView click -> Fragment Bundle replace & closeDrawer
dl1 = MockDrawerLayout({"start": {"tag": "LEFT"}})
menu_items = ["实时信息", "提醒通知", "活动路线", "相关设置"]
dl1.swipe_open("start")
picked = menu_items[2]
current_fragment = {"name": "ContentFragment", "args": {"text": picked}}
dl1.close_drawer_programmatic("start")
act2 = {
"fragment": current_fragment,
"drawer_open_after_click": dl1.drawers["start"]["open"],
"events": dl1.events,
}
exp2 = {
"fragment": {"name": "ContentFragment", "args": {"text": "活动路线"}},
"drawer_open_after_click": False,
"events": ["opened:LEFT", "prog_closed:LEFT"],
}
# Case 3: Dual-drawer LOCK_MODE_LOCKED_CLOSED / UNLOCKED & onDrawerClosed re-locking
dl2 = MockDrawerLayout({"start": {"tag": "LEFT"}, "end": {"tag": "RIGHT"}})
dl2.set_lock_mode(LOCK_MODE_LOCKED_CLOSED, "end")
dl2.on_closed_cb = lambda g: dl2.set_lock_mode(LOCK_MODE_LOCKED_CLOSED, "end") if g == "end" else None
right_swipe_blocked = dl2.swipe_open("end")
# Button click opens RIGHT programmatically and unlocks it so user can swipe close
dl2.open_drawer_programmatic("end")
dl2.set_lock_mode(LOCK_MODE_UNLOCKED, "end")
right_swipe_closed = dl2.swipe_close("end")
right_relocked_after_close = dl2.drawers["end"]["lock"] == LOCK_MODE_LOCKED_CLOSED
act3 = {
"initial_swipe_open_blocked": not right_swipe_blocked,
"swipe_close_after_unlock": right_swipe_closed,
"relocked_on_close": right_relocked_after_close,
"events": list(dl2.events),
}
exp3 = {
"initial_swipe_open_blocked": True,
"swipe_close_after_unlock": True,
"relocked_on_close": True,
"events": ["prog_opened:RIGHT", "closed:RIGHT"],
}
# Case 4: Left vs Right drawer tag discrimination in DrawerListener
dl2.swipe_open("start")
active_tags = [info["tag"] for info in dl2.drawers.values() if info["open"]]
dl2.close_drawer_programmatic("start")
act4 = {"opened_tags": active_tags, "all_closed": all(not info["open"] for info in dl2.drawers.values())}
exp4 = {"opened_tags": ["LEFT"], "all_closed": True}
cases = [
{
"name": "drawerlayout_xml_rules_audit",
"summary": "解析双抽屉 XML 核对首子视图 match_parent、start/end gravity 与 <=320dp 宽度规范",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
},
{
"name": "single_drawer_fragment_replace_and_close",
"summary": "验证单侧滑菜单点击项后通过 Bundle 参数替换主区 Fragment 并自动关闭抽屉",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
},
{
"name": "dual_drawer_lock_mode_state_machine",
"summary": "验证右侧抽屉 LOCK_MODE_LOCKED_CLOSED 禁止手势拉出、代码打开解锁后可手势关闭并自动重锁",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
},
{
"name": "drawer_tag_identification",
"summary": "验证通过 android:tag 区分左右抽屉视图状态与关闭联动",
"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-drawerlayout-lab/explore-tutorial-drawerlayout.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-drawerlayout.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1875.zip