8.4.1 Android动画合集之帧动画
核对 Android 三大动画体系分类、AnimationDrawable 逐帧动画的 XML(animation-list/oneshot)与 Java addFrame 用法、定点触控播放示例及 Android 9+ 非 SDK 反射限制替代方案。
学完这一章,你能够
- 核对 Android 三大动画体系分类、AnimationDrawable 逐帧动画的 XML(animation-list/oneshot)与 Java addFrame 用法、定点触控播放示例及 Android 9+ 非 SDK 反射限制替代方案。
Android 三大动画分类与帧动画基础
Android 视图与图形动画体系划分为三大类:逐帧动画(Frame Animation)、补间动画(Tween Animation)以及 Android 3.0(API 11)引入的属性动画(Property Animation)。其中逐帧动画利用人眼“视觉残留”效应,按预设间隔依次轮播多张静态图片形成动态效果,在 Android 中对应 `AnimationDrawable`:既可在 XML 中声明 `<animation-list>` 并设为控件背景,也可在 Java 代码中通过 `addFrame(Drawable frame, int duration)` 动态追加每一帧,随后调用 `start()` 与 `stop()` 控制启停。
循环帧动画与点击定点播放实战
基础循环示例在 `<animation-list android:oneshot="false">`(`false` 表示循环播放、`true` 仅播一次;按官方规范通常存放于 `res/drawable/`,旧工程置于 `res/anim/` 亦可被加载)中为每帧指定 `android:drawable` 与 `android:duration="80"`(毫秒)。布局中的 `ImageView` 将该资源设为 `android:background`,在 `Activity` 里通过 `(AnimationDrawable) img_show.getBackground()` 取得实例即可由按钮触发 `start()`/`stop()`。需提示:若需在页面刚打开时自动播放,不能在 `onCreate()` 中直接调用 `start()`,而应在 `onWindowFocusChanged(true)` 或 `view.post(...)` 中启动。
进阶示例将 `android:oneshot` 设为 `true`,构建自定义 `FrameView` 并添加到根 `FrameLayout`:当手指按下(`MotionEvent.ACTION_DOWN`)时先 `anim.stop()`,按触点调用 `setLocation((int)y - 40, (int)x - 20)`(内部调用 `setFrame(left, top, left + 200, top + 200)` 定位 200×200 区域),设为 `View.VISIBLE` 并重新 `anim.start()`。需特别提醒现代兼容风险:示例中 `FrameView.onDraw()` 通过反射读取 `AnimationDrawable` 私有字段 `mCurFrame` 来判断末帧隐藏,但 Android 9(API 28)起的非 SDK 接口限制会拦截此类反射,且大量大图帧易引发 OOM;工程中应改用总帧时长 `Handler.postDelayed(..., totalDuration)` 触发隐藏,或使用矢量动画 `AnimatedVectorDrawable` / Lottie 替代。来源页面附带的 `AnimationDemo1.zip`、`AnimationDemo2.zip` 与 GIF 帧提取工具压缩包均因继承停采策略未联网下载,已全部登记留痕。
运行离线 AnimationDrawable XML 帧回绕、addFrame、定点矩形及非反射收尾核验
"""Offline Android animation verifier for Ch 128: Frame Animation (AnimationDrawable)."""
from dataclasses import dataclass
import json
import xml.etree.ElementTree as ET
VERSION = "CPython 3.12.14 offline Android graphics/animation/media/service verifier (Android SDK/emulator absent)"
ANDROID_NS = "{http://schemas.android.com/apk/res/android}"
LOOP_XML = """<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@mipmap/img_miao1" android:duration="80" />
<item android:drawable="@mipmap/img_miao2" android:duration="80" />
<item android:drawable="@mipmap/img_miao3" android:duration="80" />
</animation-list>
"""
ONESHOT_XML = """<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="true">
<item android:drawable="@mipmap/img_zhuan1" android:duration="80" />
<item android:drawable="@mipmap/img_zhuan2" android:duration="80" />
<item android:drawable="@mipmap/img_zhuan3" android:duration="80" />
<item android:drawable="@mipmap/img_zhuan4" android:duration="80" />
</animation-list>
"""
@dataclass
class FrameAnim:
oneshot: bool
frames: list[tuple[str, int]]
running: bool = False
@classmethod
def from_xml(cls, xml_text: str) -> "FrameAnim":
root = ET.fromstring(xml_text)
oneshot = root.attrib.get(f"{ANDROID_NS}oneshot", "false").lower() == "true"
frames = [
(item.attrib[f"{ANDROID_NS}drawable"], int(item.attrib[f"{ANDROID_NS}duration"]))
for item in root.findall("item")
]
return cls(oneshot=oneshot, frames=frames)
def add_frame(self, drawable: str, duration: int) -> None:
self.frames.append((drawable, duration))
def total_duration(self) -> int:
return sum(d for _, d in self.frames)
def frame_at(self, elapsed_ms: int) -> tuple[int, str, bool]:
total = self.total_duration()
if self.oneshot and elapsed_ms >= total:
return len(self.frames) - 1, self.frames[-1][0], True
t = elapsed_ms % total if not self.oneshot else elapsed_ms
acc = 0
for idx, (res, dur) in enumerate(self.frames):
if t < acc + dur:
return idx, res, False
acc += dur
return len(self.frames) - 1, self.frames[-1][0], self.oneshot
def main() -> None:
# Case 1: Looping animation-list (oneshot=false) XML parsing & wrap-around playback
loop_anim = FrameAnim.from_xml(LOOP_XML)
c1_actual = {
"oneshot": loop_anim.oneshot,
"frame_count": len(loop_anim.frames),
"cycle_ms": loop_anim.total_duration(),
"frame_at_0ms": list(loop_anim.frame_at(0)),
"frame_at_150ms": list(loop_anim.frame_at(150)),
"frame_at_260ms": list(loop_anim.frame_at(260)),
}
c1_expected = {
"oneshot": False,
"frame_count": 3,
"cycle_ms": 240,
"frame_at_0ms": [0, "@mipmap/img_miao1", False],
"frame_at_150ms": [1, "@mipmap/img_miao2", False],
"frame_at_260ms": [0, "@mipmap/img_miao1", False],
}
# Case 2: Programmatic addFrame(Drawable, duration) & start/stop state
dyn = FrameAnim(oneshot=False, frames=[])
dyn.add_frame("frame_a", 100)
dyn.add_frame("frame_b", 120)
dyn.running = True
state_started = dyn.running
dyn.running = False
c2_actual = {
"dynamic_frame_count": len(dyn.frames),
"dynamic_total_ms": dyn.total_duration(),
"started_then_stopped": [state_started, dyn.running],
}
c2_expected = {
"dynamic_frame_count": 2,
"dynamic_total_ms": 220,
"started_then_stopped": [True, False],
}
# Case 3: Touch-positioned FrameView (oneshot=true, setLocation(top=y-40, left=x-20), 200x200 box)
oneshot = FrameAnim.from_xml(ONESHOT_XML)
touch_x, touch_y = 320, 440
top, left = touch_y - 40, touch_x - 20
frame_rect = [left, top, left + 200, top + 200]
last_idx, _, finished = oneshot.frame_at(320)
hide_at_last = last_idx == len(oneshot.frames) - 1
c3_actual = {
"oneshot": oneshot.oneshot,
"frame_rect_ltrb": frame_rect,
"last_frame_idx_at_320ms": last_idx,
"finished_flag": finished,
"hide_triggered": hide_at_last,
}
c3_expected = {
"oneshot": True,
"frame_rect_ltrb": [300, 400, 500, 600],
"last_frame_idx_at_320ms": 3,
"finished_flag": True,
"hide_triggered": True,
}
# Case 4: Non-reflection completion scheduling via total duration (Android 9+ hidden API safe)
safe_delay_ms = oneshot.total_duration()
c4_actual = {
"reflection_mCurFrame_restricted_api28_plus": True,
"safe_handler_delay_ms": safe_delay_ms,
}
c4_expected = {
"reflection_mCurFrame_restricted_api28_plus": True,
"safe_handler_delay_ms": 320,
}
cases = [
{
"name": "animation_list_loop_xml_playback",
"summary": "核验 oneshot=false 帧动画 XML 解析、240ms 单周期时长与循环帧索引回绕",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "programmatic_addframe_and_lifecycle",
"summary": "核验代码动态调用 addFrame(Drawable, duration) 及 start()/stop() 播放状态切换",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "touch_frameview_location_and_oneshot",
"summary": "核验点击 (320,440) 后 FrameView 定位矩形 [300,400,500,600] 与 oneshot=true 末帧隐藏",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "non_sdk_reflection_safe_completion",
"summary": "核验 Android 9+ 禁用 mCurFrame 私有字段反射后改用总时长延时回调的兼容替代",
"expected": c4_expected,
"actual": c4_actual,
"passed": c4_actual == c4_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 验证 oneshot=false 240ms 回绕、动态 addFrame、点击 (320,440) 定位 [300,400,500,600] 及总时长安全回调。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:0aaf12a8b8dd35b8eeaaf3c637a42204f708912ed2d6682cd82af3126845b029
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:ec3a76c5d406cc1bd640a905b73973121ef0aeda33c0f5508da92a4cdc526aca
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Android 9+ 设备上,为什么不建议在 `onDraw()` 中通过反射读取 `AnimationDrawable.mCurFrame` 来监听逐帧动画播放结束?应如何替代?
展开参考解答
Android 9(API 28)起限制访问非 SDK 私有字段,反射 `mCurFrame` 可能失败或抛出异常,且在 `onDraw()` 中反射开销大;可累加各帧 `getDuration(i)` 总时长通过 `Handler.postDelayed` 监听结束,或改用 `AnimatedVectorDrawable` / Lottie。